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
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.
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.
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 the
The code below demonstrates the use of the
usleep() function by delaying execution of the script by (1 second).
<?php // Current time echo "time before delay starts: "; echo date('h:i:s') . "\n"; // wait for 1 second usleep(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
<?php // Current time echo "time before delay starts: "; echo date('h:i:s') . "\n"; // wait for 10 seconds sleep(10); // back! echo "welcome back time: "; echo date('h:i:s') . "\n"; ?>
View all Courses