PHP sleep(): Delay Script Execution with Examples

Sometimes a PHP script needs to do something very productive: nothing.

The sleep() function pauses the current PHP script for a specified number of seconds. After the delay, execution continues from the next statement.

It is useful in command-line scripts, background jobs, retry logic, polling, testing slow operations, and simple request throttling. It should be used more carefully inside a normal web request because the PHP process remains occupied while the user waits.

PHP sleep() syntax

sleep(int $seconds): int

The $seconds argument is the number of whole seconds to pause execution. It must be zero or greater.

For example, the following code pauses the script for three seconds:

<?php

echo "Before sleep: " . date('H:i:s') . PHP_EOL;

sleep(3);

echo "After sleep: " . date('H:i:s') . PHP_EOL;

A possible output is:

Before sleep: 14:30:10
After sleep: 14:30:13

The script stops at sleep(3). PHP does not execute the next statement until the sleep finishes or the sleep is interrupted.

What does sleep() return?

On a normal successful sleep, sleep() returns 0.

<?php

$remainingSeconds = sleep(2);

var_dump($remainingSeconds);

The normal result is:

int(0)

If the sleep is interrupted by a signal, the function can return a non-zero value. On Unix-like systems, that value represents the number of seconds remaining. This matters mainly in CLI scripts and long-running processes that handle operating-system signals.

The exact behavior and return values are documented in the PHP sleep() manual.

sleep() vs usleep() in PHP

sleep() works with whole seconds. If you need a delay shorter than one second, use usleep() instead.

usleep() accepts microseconds. One second contains 1,000,000 microseconds.

<?php

sleep(2);        // 2 seconds
usleep(500000); // 0.5 seconds
usleep(250000); // 0.25 seconds

This distinction is important because sleep() expects an integer number of seconds. For example, this does not create a quarter-second delay:

<?php

sleep(0.25);

The value is converted to an integer, so the effective delay is zero seconds. Use usleep(250000) when you need a 250-millisecond pause.

The PHP manual documents usleep() separately for microsecond delays.

Using sleep() inside a loop

A common practical use is to pause between repeated operations. For example, a CLI script may poll the status of a background task every five seconds instead of checking continuously.

<?php

$attempt = 1;
$maxAttempts = 5;

while ($attempt <= $maxAttempts) {
    echo "Checking status. Attempt {$attempt}" . PHP_EOL;

    // Check the actual task status here.
    $taskComplete = false;

    if ($taskComplete) {
        echo "Task completed." . PHP_EOL;
        break;
    }

    if ($attempt < $maxAttempts) {
        sleep(5);
    }

    $attempt++;
}

The delay prevents the loop from running as fast as the CPU allows. That can be useful when polling a database, queue, file, or external service.

Do not use this pattern without an exit condition. A forgotten while (true) combined with sleep() can turn a harmless test script into a surprisingly loyal employee.

Using sleep() between API requests

You may also use sleep() to space requests to an external API:

<?php

$productIds = [101, 102, 103];

foreach ($productIds as $index => $productId) {
    echo "Processing product {$productId}" . PHP_EOL;

    // Make the API request here.

    $isLastItem = $index === array_key_last($productIds);

    if (!$isLastItem) {
        sleep(2);
    }
}

This creates a two-second delay between requests.

However, sleep() is not a complete API rate-limiting strategy. Real APIs may define limits per second, minute, or account, and they may return headers telling you when to retry. Follow the API’s documented rate-limit and retry rules rather than adding an arbitrary delay and hoping for the best.

sleep() blocks the current PHP execution

The most important thing to understand about sleep() is that it is blocking. The current PHP process pauses and does no useful work until the delay ends.

That is usually fine in a CLI script or a background worker. It can be a poor fit inside a normal web request.

For example, this code deliberately makes the browser wait five seconds before receiving the response:

<?php

sleep(5);

echo "Response ready.";

The visitor sees a slower page, and the PHP worker remains occupied during those five seconds. Under heavier traffic, many sleeping requests can consume available workers and reduce the number of requests your server can handle.

For long waits in web applications, it is usually better to move the work to a background job, queue, cron task, or another asynchronous process instead of keeping the HTTP request open.

sleep() and PHP execution time limits

Do not assume that sleep(30) guarantees that your script will still be allowed to run afterward.

PHP scripts can be affected by execution time limits, web-server timeouts, proxy timeouts, process manager settings, and infrastructure limits.The exact behavior also varies by platform and execution environment.

If you are deliberately writing a long-running CLI script, review your execution limits and process supervision separately. For a browser request, increasing timeouts just to accommodate long sleeps is usually a sign that the task belongs outside the request-response cycle.

Invalid values and common mistakes

In modern PHP, sleep() expects a non-negative integer.

A negative value throws a ValueError:

<?php

sleep(-1);

So validate a calculated delay before passing it to sleep():

<?php

$delay = 5;

if ($delay < 0) {
    throw new InvalidArgumentException('Delay cannot be negative.');
}

sleep($delay);

Another common mistake is using sleep() when precise timing matters. It is a request to pause for at least roughly that amount of time, not a precision timer. The operating system decides when the process gets CPU time again.

If your code needs elapsed-time measurement, use a clock function such as hrtime() or microtime(true). Do not treat sleep() itself as a timing tool.

When sleep() is a good choice

sleep() is a good fit when a simple blocking delay is intentional and the script is allowed to wait. Typical examples include CLI utilities, maintenance scripts, test scripts, polling loops, retry delays, and lightweight background jobs.

It is less suitable when the delay happens inside a user-facing web request, when many processes may sleep concurrently, or when the application needs high throughput.

The function itself is simple. The real decision is whether pausing the current PHP process is the right behavior for that part of your application.

Other PHP functions for delaying execution

sleep() is the simplest option when your delay is measured in whole seconds. PHP also provides a few related functions for more specific timing requirements.

usleep() for microseconds

Use usleep() when you need a delay shorter than one second.

<?php

// Pause for 200 milliseconds.
usleep(200000);

time_nanosleep() for finer delays

time_nanosleep() accepts separate seconds and nanoseconds values.

<?php

// Pause for 1.5 seconds.
time_nanosleep(1, 500000000);

This is useful when you need to express a delay with finer resolution than microseconds. In normal application code, sleep() or usleep() is usually easier to read.

time_sleep_until() for a specific time

time_sleep_until() pauses execution until a specified Unix timestamp. This can be clearer when you know when an action should happen rather than how long the script should wait.

<?php

$runAt = microtime(true) + 2.5;

time_sleep_until($runAt);

echo "Continuing after approximately 2.5 seconds.";

PHP documents these functions together with sleep() in its miscellaneous functions reference.

PHP sleep() FAQ

Does sleep() stop the entire server?

No. It pauses only the PHP execution that called sleep(). Other PHP processes and requests can continue running. However, a sleeping web request still occupies its worker, which is why excessive use can become a scalability problem.

Can sleep() pause for half a second?

Not directly. sleep() accepts whole seconds. Use usleep(500000) for approximately half a second.

Does sleep() use CPU while waiting?

sleep() suspends execution rather than running a busy loop continuously. That makes it much better than repeatedly checking the clock in PHP code just to create a delay.

Can I use sleep() before retrying a failed request?

Yes. A delay between retry attempts is a common use in CLI and background processes. For production retry logic, consider increasing the delay after repeated failures and respect any retry information supplied by the external service.

Should I use sleep() to schedule a task?

Usually not. Keeping a PHP process alive for minutes or hours just to wait for a future task is inefficient and fragile. Use cron, a job queue, or another scheduler for work that needs to run later.

Conclusion

PHP sleep() pauses the current script for a specified number of whole seconds. It is simple and useful for polling, retries, CLI scripts, testing, and small background tasks.

Use usleep() when you need a sub-second delay. More importantly, consider where the delay happens. A short sleep in a maintenance script is harmless. A long sleep in every web request can quickly become a server problem.

Photo of Vincy, PHP developer
Written by Vincy Last updated: August 11, 2026
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Continue Learning

These related tutorials may help you continue learning.

2 Comments on "PHP sleep(): Delay Script Execution with Examples"

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore topics
Need PHP help?