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.

JavascriptData Integrity

Code

javascriptsnippet
14 lines
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 early throw when 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

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.