reactphp / async

Async utilities and fibers for ReactPHP.
https://reactphp.org/async/
MIT License
204 stars 19 forks source link

Add new `delay()` function to delay program execution #69

Closed clue closed 1 year ago

clue commented 1 year ago

This changeset adds a new delay() function to delay program execution. This function will only return after the given number of $seconds have elapsed. Unlike PHP's sleep() function, this function may not necessarily halt execution of the entire process thread. Instead, it allows the event loop to run any other events attached to the same loop until the delay returns.

echo 'a';
React\Async\delay(1.0);
echo 'b';
// prints "a" at t=0.0s
// prints "b" at t=1.0s

This function is especially useful if you want to delay the program execution of a particular routine, such as when building a simple polling or retry mechanism. Internally, this function is implemented as the equivalent of React\Async\await(React\Promise\Timer\sleep($seconds)) but does not require any additional dependencies (https://github.com/reactphp/promise-timer/pull/51) and is arguably much easier to use.

If this PR is merged, I will backport the changes to v3 and v2. The function should work exactly the same across all versions for simple use cases, but only v4 takes advantage of fibers (#15).