Menu

Reference / Async

delay()

function
function delay(float $seconds): void

Suspend the current task for $seconds without blocking the loop.

Other tasks run meanwhile. delay(0.0) gives them a turn and returns. The wait is on a monotonic clock. Under the scheduler, sleep() and usleep() behave the same way.

Parameters

$seconds float
how long to wait, in seconds

Throws

CancelledException
when the task is cancelled

Example

use function Async\async;
use function Async\delay;
use function Async\spawn;

// async() runs the callable on the engine and returns its value.
$total = async(function () {
    // spawn() starts a task in the current scope and returns a handle.
    $slow = spawn(function () {
        delay(0.02);
        return 10;
    });
    $fast = spawn(function () {
        delay(0.01);
        return 32;
    });

    // await() suspends this task (not the process) until the other one settles.
    return $slow->await() + $fast->await();
});

echo "total: $total\n";

Output

total: 42

View source