Is there a function similar to setTimeout() (JavaScript) for PHP?

Viewed 99564

The question sort of says it all - is there a function which does the same as the JavaScript function setTimeout() for PHP? I've searched php.net, and I can't seem to find any...

10 Answers

There is a Generator class available in PHP version > 5.5 which provides a function called yield that helps you pause and continue to next function.

generator-example.php

    <?php
    function myGeneratorFunction()
    {
        echo "One","\n";
        yield;

        echo "Two","\n";
        yield;

        echo "Three","\n";
        yield;
    }

    // get our Generator object (remember, all generator function return
    // a generator object, and a generator function is any function that
    // uses the yield keyword)
    $iterator = myGeneratorFunction();

OUTPUT

One

If you want to execute the code after the first yield you add these line

    // get the current value of the iterator
    $value = $iterator->current();

    // get the next value of the iterator
    $value = $iterator->next();

    // and the value after that the next value of the iterator
    // $value = $iterator->next();

Now you will get output

One
Two

If you minutely see the setTimeout() creates an event loop.

In PHP there are many libraries out there E.g amphp is a popular one that provides event loop to execute code asynchronously.

Javascript snippet

setTimeout(function () {
    console.log('After timeout');
}, 1000);

console.log('Before timeout');

Converting above Javascript snippet to PHP using Amphp

Loop::run(function () {
    Loop::delay(1000, function () {
        echo date('H:i:s') . ' After timeout' . PHP_EOL;
    });
    echo date('H:i:s') . ' Before timeout' . PHP_EOL;
});

enter image description here

Check this Out!

<?php

set_time_limit(20);

while ($i<=10)
{
        echo "i=$i ";
        sleep(100);
        $i++;
}

?>

Output: i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10

Related