Debounce function
// Set up debounced handler
const moveDebounced = debounce((evt) => {
// Handle event
}, 500);
// Wire up event
el.addEventListener(`pointermove`, moveDebounced);
Arguments can be passed to the debounced function:
const fn = (x) => console.log(x);
const d = debounce(fn, 1000);
d(10);
If you want the result of a debounced function when it finally executes, pass
in the onResult parameter:
const isRed = (colour) => colour === `red`;
const onResult = (result) => {
if (result.success) {
console.log(`Value: ${result.value}`);
}
}
const d = debounce(fn, 1000, onResult);
Note that only the onResult handler for the function call that succeeeds is called,
there's no queuing of callbacks.
If the debounced function throws an error, this will be reported as well:
if (!result.success) {
console.error(result.error);
}
Returns a debounce function which acts to filter calls to a given function
fn.Eg, Let's create a debounced wrapped for a function:
Now we can call
debouncedFn()as often as we like, but it will only executefn()after 1 second has elapsed since the last invocation. It essentially filters many calls to fewer calls. Each timedebounceFn()is called, the timeout is reset, so potentiallyfncould never be called if the rate ofdebounceFnbeing called is faster than the provided timeout.Remember that to benefit from
debounce, you must call the debounced wrapper, not the original function.A practical use for this is handling high-frequency streams of data, where we don't really care about processing every event, only last event after a period. Debouncing is commonly used on microcontrollers to prevent button presses being counted twice.