0
0
PhpHow-ToBeginner · 3 min read

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 0 on success or false on 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 sleep in web scripts without considering user experience, as it delays the response.
  • Expecting sleep to pause for fractions of a second (use usleep for microseconds).
php
<?php
// Wrong: passing float
sleep(1.5); // Warning or truncates to 1

// Right: passing integer
sleep(1);
?>
📊

Quick Reference

FunctionDescriptionParameterReturn
sleepPauses script executionInteger seconds0 on success, false on failure
usleepPauses script for microsecondsInteger microsecondsvoid

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.