Debounce With Trailing Edge Invocation
A debounce utility that collapses rapid calls into one trailing invocation with flush and cancel support for deterministic tests.
Code
export function debounce(fn, waitMs, scheduler = setTimeout) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isFinite(waitMs) || waitMs <= 0) throw new RangeError("waitMs must be a positive number");
let timer = null;
let lastArgs = null;
const wrapped = (...args) => {
lastArgs = args;
if (timer !== null) clearTimeout(timer);
timer = scheduler(() => {
timer = null;
const a = lastArgs;
lastArgs = null;
fn(...a);
}, waitMs);
};
wrapped.flush = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
if (lastArgs !== null) {
const a = lastArgs;
lastArgs = null;
fn(...a);
}
};
wrapped.cancel = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
lastArgs = null;
};
return wrapped;
}Search-as-you-type fires a request per keystroke, wasting bandwidth and racing responses.
Use case: frontend and CLI developers throttling noisy event sources
Inputs / outputs
- Input: a function, wait milliseconds, optional scheduler
- Output: debounced wrapper with flush() and cancel()
Error conditions
- wait is not a positive number
- cancel called before any invocation
Approach
trailing-edge timer; each call resets the timer; flush runs immediately and clears the pending timer; cancel drops the pending call.
Implementation
export function debounce(fn, waitMs, scheduler = setTimeout) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isFinite(waitMs) || waitMs <= 0) throw new RangeError("waitMs must be a positive number");
let timer = null;
let lastArgs = null;
const wrapped = (...args) => {
lastArgs = args;
if (timer !== null) clearTimeout(timer);
timer = scheduler(() => {
timer = null;
const a = lastArgs;
lastArgs = null;
fn(...a);
}, waitMs);
};
wrapped.flush = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
if (lastArgs !== null) {
const a = lastArgs;
lastArgs = null;
fn(...a);
}
};
wrapped.cancel = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
lastArgs = null;
};
return wrapped;
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { debounce } from "./example.mjs";
test("collapses rapid calls into one trailing invocation", async () => {
let calls = 0;
const d = debounce(() => { calls += 1; }, 20);
d("a"); d("b"); d("c");
await new Promise((r) => setTimeout(r, 40));
assert.equal(calls, 1);
});
test("flush invokes pending work immediately", () => {
const seen = [];
const d = debounce((x) => seen.push(x), 1000);
d("x");
assert.deepEqual(seen, []);
d.flush();
assert.deepEqual(seen, ["x"]);
d.flush();
assert.deepEqual(seen, ["x"]);
});
test("cancel drops the pending call", async () => {
let calls = 0;
const d = debounce(() => { calls += 1; }, 10);
d();
d.cancel();
await new Promise((r) => setTimeout(r, 30));
assert.equal(calls, 0);
});
test("invalid wait is rejected", () => {
assert.throws(() => debounce(() => {}, 0), RangeError);
assert.throws(() => debounce(() => {}, -5), RangeError);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node example.mjs
Limitations and error handling
no leading-edge invocation; no maxWait guarantee.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.