-
Notifications
You must be signed in to change notification settings - Fork 0
Library: delay()
Eugene Lazutkin edited this page Jul 11, 2018
·
2 revisions
delay() module is a function, which cancels calls to a controlled function within a time window, then restart a timer again. A function will be called after a time window has expired unless another call was made. In this case, the pending call is canceled and a new timer is initialized. Ultimately only the last call will succeed if previous calls canceled each other.
The definition is trivial:
const delay = (f, ms = 50) => {
let handle, savedArgs;
return (...args) => {
savedArgs = args;
if (handle) {
clearTimeout(handle);
}
handle = setTimeout(() => {
const args = savedArgs;
handle = savedArgs = null;
f(...args);
}, ms);
};
};In a module-enabled environment (like Babel) it can be accessed like that:
import delay from '@researchnow/reno/src/utils/delay';In global-based environments (like a browser) it is frequently mapped to Reno.utils.delay.
The function takes the following arguments:
-
fis a controlled function. The access to this function is going to be delayed. It can take any number of arguments but its return value will be ignored. -
msis a positive integer, which specifies a delay time in milliseconds.
Do a service call only when a user has finished entering data at least for 750 milliseconds:
const doServiceCall = delay(serviceCall, 750);
// ...
input.addEventListener('input', evt => doServiceCall(evt.target.value));