How to Use Sleep Function in PHP: Syntax and Examples
In PHP, you use the
sleep function to pause the script for a specified number of seconds. Just call sleep(seconds) where seconds is an integer representing how long the script should wait before continuing.Syntax
The sleep function pauses the execution of the PHP script for a given number of seconds.
- seconds: The number of seconds to pause. It must be an integer.
- The function returns
0on success orfalseon failure.
php
int sleep(int $seconds);
Example
This example shows how to pause the script for 3 seconds before printing a message.
php
<?php echo "Start\n"; sleep(3); echo "End after 3 seconds\n"; ?>
Output
Start
End after 3 seconds
Common Pitfalls
Common mistakes when using sleep include:
- Passing a non-integer value, which will cause a warning or unexpected behavior.
- Using
sleepin web scripts without considering user experience, as it delays the response. - Expecting
sleepto pause for fractions of a second (useusleepfor microseconds).
php
<?php // Wrong: passing float sleep(1.5); // Warning or truncates to 1 // Right: passing integer sleep(1); ?>
Quick Reference
| Function | Description | Parameter | Return |
|---|---|---|---|
| sleep | Pauses script execution | Integer seconds | 0 on success, false on failure |
| usleep | Pauses script for microseconds | Integer microseconds | void |
Key Takeaways
Use
sleep(seconds) to pause PHP script execution for whole seconds.Pass only integer values to
sleep to avoid warnings.For delays shorter than one second, use
usleep instead.Avoid using
sleep in web requests where it can slow down user experience.The function returns 0 on success and false on failure.