A simple & classic debounce function. You provide a callable and specify a $wait timer and get a callable (closure) back.
The closure takes the same arguments as the provided callable, but will only be executed $wait seconds after being invoked. Invoking the closure again before $wait seconds have passed will refresh the execution delay to the full $wait seconds again.
This can be useful for example for detecting if a socket hasn't received data in, let's say, 10 seconds:
$loop = React\EventLoop\Factory::create();
$receivedData = Debouncer::debounce($loop, 10, function () {
echo "You have not received data in a while! Check your connection please.";
});
// Delay the connection warning on any data received
$someConnection->on('data', $receivedData);
// Make sure the delay timer is set up initially
$receivedData();
$loop->run();Let's stick with the $receivedData function from above.
To invoke the function (and thus refresh the delay timer), you may call the ->invoke() method:
$receivedData->invoke();
// Thanks to the __invoke() magic method, this does the same:
$receivedData();Calling isPending() will tell if the function was invoked but has not been executed yet:
$receivedData->isPending(); // false
$receivedData->invoke();
$receivedData->isPending(); // true, will be executed in 10 secondsSometimes you want a debounced function to stop it's job and also make sure no delayed action will be executed (think canceling a Promise). This can be done as follows:
$receivedData->invoke();
$receivedData->cancelPending();
// Delayed action will never be executed