Trusted answers to developer questions

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

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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μs1000000\mu s (1 second).

Press + to interact
<?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 10 seconds.

Press + to interact
<?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";
?>

RELATED TAGS

php
web development
Did you find this helpful?