Timed Delay in C++
To add a timed delay in C++, we can use the std::this_thread::sleep_for() function from the <thread> library. Pass the duration of the delay as a parameter to the sleep_for() function using chrono::seconds(), which will pause the execution of the program for the specified duration.
Syntax to Use sleep_for Function
this_thread::sleep_for(chrono::duration(time_period));
Here,
- duration can be in various time units like seconds, milliseconds, microseconds, etc.
- time_period is the duration of time for which the current thread is put to sleep.
Note: Due to scheduling and other system factors, the actual sleep time may be longer than the specified time.
C++ Program to Add Timed Delay
The below program demonstrates how we can add timed delay in C++.
// C++ program to Add Timed Delay in C++?
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
int main()
{
// Printing the initial message
cout << "Starting the countdown..." << endl;
// Countdown loop from 5 to 1
for (int i = 5; i > 0; --i) {
// Printing the remaining seconds
cout << i << " seconds remaining" << endl;
// Waiting for 1 second
this_thread::sleep_for(chrono::seconds(1));
}
// Printing the final message
cout << "Time's up!" << endl;
return 0;
}
Output
Starting the countdown...
5 seconds remaining
4 seconds remaining
3 seconds remaining
2 seconds remaining
1 seconds remaining
Time's up!
Note: The this_thread::sleep_for() function is part of the C++11 standard, it may not work on older compilers that does not support C++11 and later.
How to Add Timed Delay in C++?
In C++, there is the functionality of delay or inactive state which allows the execution to be delayed for a specific period of time. This is often referred to as a “timed delay”. In this article, we will learn how to add timed delay in C++.