The php sleep() function gives us the ability to pause the execution of our code. sleep() delays the execution of code by a given number of seconds.
sleep(30); // program sleeps for 30 seconds
When programming in php, sometimes we want to delay the execution of a piece of code so that other processes can catch up or complete.
We can use the php sleep() function to delay the execution of code in php.
sleep() takes one parameter which is the number of seconds you want to sleep your code.
Below is an example of how to use sleep() in php.
echo date("Y-m-d H:i:s") . "n";
sleep(30); // program sleeps for 30 seconds
echo date("Y-m-d H:i:s") . "n";
// Output:
2022-04-06 08:11:27
2022-04-06 08:11:57
Using usleep() function in php to Delay Execution by Microseconds
If you need to sleep the code for less than a second, or want to use fractions of a second, then you can use the php usleep() function.
The usleep() function has the same behavior as sleep() but instead of seconds, we pass microseconds.
Below is an example of how to use usleep() to pause the execution of your code in php.
echo date("Y-m-d H:i:s") . "n";
usleep(1000000); // program sleeps for 1 seconds
echo date("Y-m-d H:i:s") . "n";
// Output:
2022-04-06 08:12:27
2022-04-06 08:12:28
Hopefully this article has been useful for you to understand how to use the php sleep() function.