How to Delay PHP Script Execution with sleep()
This article explains how to pause or delay the execution of a PHP
script using the built-in sleep() function. You will learn
the basic syntax, see practical code examples, and understand how to
delay execution by seconds or microseconds using related functions.
Understanding the PHP sleep() Function
The sleep() function in PHP is a built-in tool used to
halt the execution of a script for a specified number of seconds. Once
the designated time passes, the script resumes execution from the very
next line. This is useful for rate-limiting API requests, pausing
between batch email dispatches, or simulating loading delays during
testing.
Syntax
sleep(int $seconds): int$seconds: The number of seconds to halt the script. This must be a non-negative integer.- Return Value: Returns
0on success, orfalseon error. If the call is interrupted by a signal,sleep()returns a non-zero value.
Code Example: Delaying Execution by Seconds
Below is a simple example showing how to delay a script’s output by 5 seconds.
<?php
echo "Script started at: " . date('h:i:s') . "\n";
// Delay the script for 5 seconds
sleep(5);
echo "Script resumed at: " . date('h:i:s') . "\n";
?>In this example, the current time is printed, the script pauses for 5 seconds, and then the final timestamp is printed, showing a 5-second difference.
Delaying Execution by Microseconds
Because the sleep() function only accepts integers, you
cannot use it to delay execution for a fraction of a second (like 1.5
seconds). To achieve sub-second delays, use the usleep()
function, which pauses execution in microseconds (1 second = 1,000,000
microseconds).
Code Example: Delaying for 1.5 Seconds
<?php
echo "Start: " . date('h:i:s') . "\n";
// Delay for 1.5 seconds (1,500,000 microseconds)
usleep(1500000);
echo "End: " . date('h:i:s') . "\n";
?>Important Considerations
- Execution Time Limits: PHP scripts have a default maximum execution time (often 30 seconds). Time spent sleeping generally does not count toward the CPU limit on most platforms, but it can still trigger gateway timeouts (like a 504 Gateway Timeout) on web servers like Nginx or Apache if the overall connection takes too long.
- Output Buffering: If you want to output text to the
browser before a
sleep()command runs, you may need to clear the output buffer usingflush()andob_flush(). Otherwise, the browser will wait until the entire script finishes executing before displaying any content.