Function to filter access to
Minimum time between invocations
Debounce function
// Set up debounced handler
const moveDebounced = debounce((elapsedMs, 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 the provided function is asynchronous, it's possible to await the debounced version as well. If the invocation was filtered, it returns instantly.
const d = debounce(fn, 1000);
await d();
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 potentiallyfn
could never be called if the rate ofdebounceFn
being 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.