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

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