sleep() function in PHP

The sleep() function delays execution of the current script for a specified number of seconds. This is useful for creating pauses in script execution, rate limiting, or simulating delays.

Syntax

sleep(seconds)

Parameters

  • seconds − The number of seconds to delay the script (integer value).

Return Value

The sleep() function returns zero on success, or FALSE on failure.

Example

Here's a simple example demonstrating how sleep() pauses script execution −

<?php
   echo "Start time: " . date('h:i:s') . "<br>";
   
   // wait for 2 seconds
   sleep(2);
   echo "After 2 seconds: " . date('h:i:s') . "<br>";
   
   // wait for 3 more seconds
   sleep(3);
   echo "After 3 more seconds: " . date('h:i:s') . "<br>";
?>
Start time: 02:54:50
After 2 seconds: 02:54:52
After 3 more seconds: 02:54:55

Common Use Cases

  • Rate Limiting − Preventing too many API calls or requests

  • Simulation − Creating realistic delays in testing environments

  • Batch Processing − Adding delays between processing large datasets

Key Points

  • Script execution is completely paused during sleep()

  • For sub-second delays, use usleep() for microseconds

  • The function may sleep longer than specified due to system activity

Conclusion

The sleep() function is essential for controlling script timing and creating intentional delays. Use it wisely to avoid unnecessarily slowing down your applications.

Updated on: 2026-03-15T07:37:48+05:30

860 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements