Using PHP Sleep Like Javascript setTimeout: 2023 Code Examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Use the Sleep() function in PHP

PHP sleep() halts a running script for specific seconds. It is a synchronous and blocking timer that may surprise you if you switch from an async context. Let’s quickly go through some highlights and clarify some presumptions..

PHP Sleep Function Code Example

<?php


/*
@params
$fn - callback function
$seconds - halt time in seconds (expects an integer greater than or equal to zero)
*/
function setTimeout($fn, $seconds){
    sleep($seconds);
    $fn();
}


$greet = function() {
    echo 'Hello' . "\n";
};


echo "Before calling setTimeout() ".date('h:i:s') . "\n";
setTimeout($greet, 5);
echo "After timeout ".date('h:i:s') . "\n";


/*
Before calling setTimeout() 07:44:18
Hello
After timeout 07:44:23
*/
?>

Article Highlights

  • An asynchronous & non-blocking timer doesn’t block a thread but puts off the execution of a function for a defined timeout duration.
  • PHP sleep() function is not an asynchronous function; therefore, it blocks the thread of execution.
    PHP doesn’t have an event loop out of the box. It is not asynchronous, so setTimeout() and setInterval() may not make much sense.
  • setInterval() using sleep() initiates an infinite loop with no way of stopping it other than manually killing the program.

Table of Contents

Use the PHP Sleep Function in PHP

What is the sleep() Function in PHP?

PHP sleep() function delays the execution of a code in seconds. It was first introduced in PHP 4. Developers use this function whenever they need to pause a script like requesting API calls to avoid excessive rate limits. Using the function is controversial because some developers consider it a code smell.

When to Use PHP Sleep Examples

  • Implementing rate limiting in API calls to avoid excessive traffic
  • Coordinating concurrent processes to avoid resource conflicts
  • Temporarily delaying script execution to ensure dependent services are fully initialized before continuing
  • Simulating long-running processes for testing purposes

Syntax

sleep(int $seconds): int

Parameter

seconds – Halt time in seconds (Expects an integer greater than or equal to 0)

Errors/Exceptions

This function returns a ValueError if the specified seconds are less than 0.

Using the PHP sleep() Function to Pause Running Code Example

Let’s see a basic example of how to pause a script using the PHP sleep() function.

<?php


// current time
echo "Before sleep() ".date('h:i:s') . "\n";


// sleep for 5 seconds
sleep(5);


// wakes up after 5 seconds !
echo "After sleep() ".date('h:i:s') . "\n";


/*
Before sleep() 07:13:15
After sleep() 07:13:20
*/


?>

setTimeout() Example using PHP Sleep() Function

If you’re coming from Javascript then setTimeout() is perhaps a known function to you. It is asynchronous in nature and delays the execution of a function for a specified period of time. Meanwhile, it doesn’t block the thread and continues executing the rest of the script.

php sleep

In contrast, the PHP sleep() function is not an asynchronous function; therefore, it blocks the thread of execution. So, it is generally not a bright idea to block a thread unless there is some use case where you actually have to. 

So sleep() function can be thought of as a blocking timer, and since PHP is not event-driven and thus non-blocking timers are a rare sight. However, some libraries feature an event loop for PHP, similar to what we have in Javascript. But that’s not the topic here.

Anyways, we will still mimic setTimeout() using the sleep() function, but always keep in mind that it is drastically different from the async setTimeout() in Javascript.

<?php


/*
@params
$fn - callback function
$seconds - halt time in seconds (expects an integer greater than or equal to zero)
*/
function setTimeout($fn, $seconds){
    sleep($seconds);
    $fn();
}

?>

So, this function will execute the callback function $fn after a specified period of time in seconds. 

Let’s define a function and pass it to setTimeout(). We would specify a halt time of 5 seconds.

<?php


/*
@params
$fn - callback function
$seconds - halt time in seconds (expects an integer greater than or equal to zero)
*/
function setTimeout($fn, $seconds){
    sleep($seconds);
    $fn();
}


$greet = function() {
    echo 'Hello' . "\n";
};




echo "Before calling setTimeout() ".date('h:i:s') . "\n";
setTimeout($greet, 5);
echo "After timeout ".date('h:i:s') . "\n";


/*
Before calling setTimeout() 07:44:18
Hello
After timeout 07:44:23
*/
?>

While much of it is self-explanatory but notice that the execution is hanged and resumes after the timeout.

If it had been an async function, the execution won’t have halted but immediately passed on to the next line after setTimeout($greet, 5). As a result, the output will be as follows.

/*
Before calling setTimeout() 07:44:18
After timeout 07:44:18
Hello
*/

setTimeout() with Parameters Example using PHP Sleep() Function Example

We can also pass arguments to the callback function via setTimeout() using the splat operator in PHP (PHP 5.6.x and above).

<?php


/*
@params
$fn - callback function
$seconds - halt time in seconds (expects an integer greater than or equal to zero)
$args (Optional) - callback function arguments
*/
function setTimeout($fn, $seconds, ...$args)
{
        sleep($seconds);
        $fn(...$args);
}


$greet = function($name) {
    echo "Hello " . $name ." " . "\n";
};


setTimeout($greet, 5, "Tom");


/*
Hello Tom
*/
?>

setInterval() Code Example using PHP sleep() Function

You may familiar with setInterval() from Javascript. It is also an async function that repeatedly invokes a callback function after a specified interval unless you stop it from doing so by calling clearInterval()

Here’s setInterval() using PHP sleep(). Beware that it is a blocking timer and doesn’t behave like setInterval() from Javascript.

<?php


/*
@params
$fn - callback function
$seconds - halt time in seconds (expects an integer greater than or equal to zero)
*/
function setInterval($fn, $seconds)
{
    while(true)
    {
        $fn();
        sleep($seconds);
    }
}


$greet = function() {
    echo "Hello". "\n";
};


setInterval($greet, 5);


/*
Hello
Hello
Hello
[Terminated Output]
*/
?>

The script won’t stop at all and prints “Hello” indefinitely at 5 seconds intervals. Also, there is no way to stop it other than manually killing the program. Function like clearInterval() works in an async context.

Pause Script for 1 Second PHP Example

Can you halt a PHP script for one second? Try it on your own and then compare it with the following example.

<?php


// current time
echo "Before sleep() ".date('h:i:s') . "\n";




// sleep for 1 second
sleep(1);




// wakes up after 1 second !
echo "After sleep() ".date('h:i:s') . "\n";




/*
Before sleep() 08:22:34
After sleep() 08:22:35
*/


?>

Run a Script every 5 Minutes PHP Example

Yet another interesting example. Be mindful of the blocking behavior, though. We can use our custom setInterval() with an interval of 300 seconds (5 minutes).

<?php


/*
@params
$fn - callback function
$seconds - halt time in seconds (expects an integer greater than or equal to zero)
*/


function setInterval($fn, $seconds)
{
    while(true)
    {
        $fn();
        sleep($seconds);
    }
}


$greet = function() {
    echo "Hello". "\n";
};




$interval = setInterval($greet, 300);


/*
Hello
Hello
Hello
[Terminated Output]
*/
?>

Why use the PHP sleep() Function?

PHP sleep() function halts code execution for a specified period of time in seconds. If you are coming from an async programming context, it is extremely important that you understand that sleep() blocks the thread.

So, when we say setInterval() in PHP using sleep(), it is an entirely different thing from the async setInterval() function. The former will halt the program, execute the callback and then resume the script, but the latter schedules a function execution and keep on going with the rest of the script.

Similarly, setInterval() is yet another async function popular among JS developers, but when it comes to the PHP sleep() function, expect an entirely different behavior because the script is stuck in one block and executes the callback indefinitely. Also, there is no way to stop this, just as we have clearInterval() in JS, other than manually killing the program.

In summary, many of these functions won’t run as expected if you switch from an async context. However, some libraries feature event loops for PHP, where you can do async programming just the way you expect in JS via the event loop and promises.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources.

We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Learn More About Dates in PHP

This article is part of our continuing series on dates in PHP. Check out the other articles to discover everything you need to know about working with dates & time in PHP.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.