Computer programs help us to control computing devices almost absolutely. As you write these programs in PHP, you are equipped with many inbuilt functions that let you carry out a lot of manipulations off the shelf. Examples of such functions are the sleep()
and usleep()
functions.
Just as their names imply, these functions are used to delay code execution of scripts. With these functions, you can tell your script to basically pause script execution when they are encountered for a number of seconds or microseconds.
It is most important to use these on scripts that start to execute after the system starts. You can prevent the problems of such conditions by delaying the script’s execution.
The sleep()
function will delay the script’s execution in seconds while usleep()
will delay it in microseconds.
Both functions are supported by PHP 4 and later versions.
For sleep()
:
sleep($seconds)
For usleep()
:
usleep($microseconds)
The sleep()
and usleep()
functions both accept a compulsory integer parameter, which is the delay duration in seconds and microseconds respectively.
Both functions do not return any value, and the time delay may vary from machine to machine.
Note: When using
usleep()
, try not to set the delay to more than a second. For such durations, use thesleep()
function instead.
The code below demonstrates the use of the usleep()
function by delaying execution of the script by (1 second).
<?php// Current timeecho "time before delay starts: ";echo date('h:i:s') . "\n";// wait for 1 secondusleep(1000000);// back!echo "welcome back time: ";echo date('h:i:s') . "\n";?>
In the example below, we use the sleep()
function to delay the execution of the script by 10
seconds.
<?php// Current timeecho "time before delay starts: ";echo date('h:i:s') . "\n";// wait for 10 secondssleep(10);// back!echo "welcome back time: ";echo date('h:i:s') . "\n";?>