repeat() & delay()

    /**
     * @param callable $callback
     * @param int $times
     * @return Closure
     *
     * This is a generator that runs a callback function a specified amount of times.
     */
    public static function repeat(callable $callback, int $times) : Closure;

    /**
     * @param int $milliseconds
     * @return Generator
     *
     * This is a generator that yields for a specified amount of milliseconds.
     */
    public static function delay(int $milliseconds) : Generator;

These are 2 functions that should only be used in a Coroutine Scope or a runBlocking().

CoroutineGen::runBlocking(
    function() : Generator {
        yield from CoroutineGen::delay(3000);
        var_dump("A");
    },
    CoroutineGen::repeat(function() {
        yield from CoroutineGen::delay(100);
        var_dump("B");
    }, 5),
    function() {
        var_dump("C");
    },
    $launch = CoroutineGen::launch(
        CoroutineGen::launch(function() {
            yield from CoroutineGen::delay(1000);
            var_dump("D");
        })
    ),
    function() use ($launch) : Generator {
        yield from CoroutineGen::delay(3000);
        $launch->cancel();
        var_dump("E");
    },
    CoroutineGen::launch(
        CoroutineGen::launch(function() : void {
            var_dump("F");
        }),
        function() {
            var_dump("G");
        }
    ),
    function() {
        var_dump("H");
    }
);

Output:

string(1) "B"
string(1) "B"
string(1) "B"
string(1) "B"
string(1) "B"
string(1) "F"
string(1) "G"
string(1) "C"
string(1) "H"
string(1) "D"
string(1) "A"
string(1) "E"
float(7.04588418006897)

Last updated