promise-timer
promise-timer copied to clipboard
Provide function that combines `sleep()` and `timeout()`
For an event-driven API with user interactions, I need to provide endpoints that delay the response for a while to wait for potential interactions and take an action once a timeout is reached.
I've implemented something in a possibly hacky way and believe it would be a potential feature for this lib:
namespace React\Promise\Timer;
use Closure;
use function React\Async\async;
use function React\Async\await;
/**
* @param Closure():bool $stopCondition,
* @param Closure():void $onTimeout
*/
function waitUntil(
Closure $stopCondition,
float $verificationInterval,
Closure $onTimeout,
float $timeout,
): void {
try {
$wait = async(static function () use ($stopCondition, $verificationInterval): void {
while (! $stopCondition()) {
await(sleep($verificationInterval)); // Timer\sleep() btw
}
});
await(timeout($wait(), $timeout)); // Timer\timeout() btw
} catch (TimeoutException) {
$onTimeout();
}
}
You certainly have ideas on how to turn this into a decent feature or just bin it. I'm happy either way 😂
Hey @lcobucci, already a win if this helps you with your project 👍
Whether this will be a new feature or not depends on how many people need this for their use cases. If there's a demand for this I can see this as a future addition to the project. ^^
I completely understand it, my goal was mostly sharing and/or picking your brains. That solution works for me, which is enough atm 😂