Debounce a Function
Debounce wraps a callback so it runs only after activity stops for a set wait, collapsing bursts of calls into a single trailing invocation.
Code
export function debounce(fn, waitMs) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (waitMs < 0) throw new RangeError("waitMs must be >= 0");
let timer = null;
let lastArgs = null;
return function debounced(...args) {
lastArgs = args;
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, lastArgs);
}, waitMs);
};
}Report a problem with this exampleOpens a pre-filled issue on GitHub.