Menu

Reference / Async

timeout()

function
function timeout(float $seconds, callable $body): mixed

Run $body in a scope that must finish within $seconds.

On expiry the whole scope, meaning the body and everything it spawned, is cancelled and joined, and then TimeoutException is thrown. A timeout that leaves work running is not a timeout. The deadline is visible inside through Context::remaining(), and a nested timeout() can only tighten an enclosing one: a 30 second scope inside a 2 second one still ends at 2 seconds. Deadlines use a monotonic clock, so clock changes do not move them.

$page = Async\timeout(2.0, fn() => file_get_contents($url));

The deadline is cooperative: the body must reach a suspend point for it to be enforced. A purely CPU-bound body should call Context::throwIfCancelled() at its loop head.

Parameters

$seconds float
the time budget, in seconds
$body callable
called with the timeout's TaskGroup

Returns

mixed — the value returned by $body

Throws

TimeoutException
when the deadline passed first
\LogicException
outside async()
\Throwable
whatever $body or a task it spawned threw

Example

use Async\CancelledException;
use Async\TimeoutException;
use function Async\async;
use function Async\delay;
use function Async\spawn;
use function Async\timeout;

async(function () {
    // The body finishes in time: timeout() just returns its value.
    echo timeout(1.0, fn() => "in time") . "\n";

    // The deadline expires: the body AND everything it spawned are cancelled
    // and joined before TimeoutException is thrown.
    try {
        timeout(0.05, function () {
            spawn(function () {
                try {
                    delay(10.0);
                } catch (CancelledException $e) {
                    echo "child cancelled\n";
                    throw $e;
                }
            });
            delay(10.0);
        });
    } catch (TimeoutException $e) {
        echo "timed out\n";
    }
});

Output

in time
child cancelled
timed out

See also: Task::awaitWithin, Context::remaining

View source