Related Tags

php
web development
communitycreator

What are sleep() and usleep() functions in PHP?

NDUKWE CHIDERA K.

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.

Functionality

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.

Difference

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.

Syntax

For sleep():

sleep($seconds) For usleep(): usleep($microseconds)

Parameters

The sleep() and usleep() functions both accept a compulsory integer parameter, which is the delay duration in seconds and microseconds respectively.

Return value

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 sleep() function instead.

Code

The code below demonstrates the use of the usleep() function by delaying execution of the script by $1000000\mu s$ (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";

?>
Delay using usleep()

In the example below, we use the sleep() function to delay the execution of the script by 10 seconds.

<?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";

?>
Delay using sleep()

RELATED TAGS

php
web development
communitycreator

CONTRIBUTOR

NDUKWE CHIDERA K.
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time