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);
};
}How the snippet works
Structurally, expect the functions debounce and debounced and nothing else.
Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.
Points of care
- The guard
typeof fn !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The primary signature is export function debounce(fn, waitMs)
Callers only need debounce — everything else stays internal.
Statements that matter
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (waitMs < 0) throw new RangeError("waitMs must be >= 0");
return function debounced(...args) {
lastArgs = args;
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn.apply(this, lastArgs);
}, waitMs);
};
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does the snippet do with malformed data?
- The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `debounce`, `debounced` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.