Debounce
Debouncing delays work until the activity that triggered it has stopped, and it is the most asked implementation question in front-end interviews.
A debounced function resets its timer on every call and only runs once the calls stop for a given interval. Built from a closure holding a timer id. The details that separate a working version from a passable one are this, the arguments, and cancellation.
EXERCISE
1The Problem, and the Eight Lines That Solve It
Some events fire far more often than the work they trigger can sensibly run.
The problem:
input.addEventListener("input", (event) => {
search(event.target.value);
});
Typing "" fires ten events and sends ten requests. Nine of them are for prefixes nobody wanted results for, and the responses can arrive out of order, so the results for "javas" may land after the results for "javascript" and overwrite them.
What you actually want is one search, after the typing stops.
The implementation:
function debounce(fn, delay) {
let timerId = null;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
const debouncedSearch = debounce(search, 300);
input.addEventListener("input", (event) => {
debouncedSearch(event.target.value);
});
Every line is carrying something:
// let timerId = null;
// Lives in the closure, so it survives between calls and is
// private to this debounced function. Two debounced functions
// have two independent timers.
// clearTimeout(timerId);
// Cancels the pending run. This is the whole mechanism: each
// call throws away the previous plan. Clearing a timer that
// already fired or never existed is safe, so no check is needed.
// function (...args)
// A normal function, not an arrow, so it has its own `this`.
// fn.apply(this, args)
// Forwards both. Unit 2's material: without this, a debounced
// method loses its object, and without args the handler gets
// nothing.
Watching it behave:
const log = debounce((msg) => console.log(msg), 300);
log("a"); // scheduled
setTimeout(() => log("b"), 100); // cancels "a", schedules "b"
setTimeout(() => log("c"), 200); // cancels "b", schedules "c"
// 500ms after the start: "c"
// "a" and "b" never ran.
Only the last call in a burst survives, which is the definition.
Worth pausing on why cancelling is the whole trick. A debounced function does not count calls or compare timestamps. It keeps one plan, and every new call throws that plan away and makes another. Whatever plan survives the burst is the one that runs, which is why the implementation is this short and why it has no edge cases to speak of.
Where it fits:
// A search box, so one request happens after typing stops.
// A window resize handler, so layout recalculates once.
// Autosave, so a draft is saved a moment after editing pauses.
// A form validation that hits the server.
The common thread is that intermediate states are worthless and only the final one matters.
Pro Tip: Create the debounced function once, outside the handler. Calling
debounce(fn, 300)inside an event listener builds a new function with a fresh timer on every event, so nothing is ever cancelled and every call runs. It looks almost identical and does nothing at all, which makes it a genuinely nasty bug.
EXERCISE
2The Details That Separate the Versions
The eight-line version works. Three additions make it something you would actually ship.
One: the ability to cancel.
function debounce(fn, delay) {
let timerId = null;
function debounced(...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
debounced.cancel = function () {
clearTimeout(timerId);
timerId = null;
};
return debounced;
}
Attaching a method to the returned function works because a function is an object, as Unit 1 showed. Without cancel, a component that unmounts leaves a pending call that fires into something no longer there, which is the leak from Unit 9.
// on teardown
debouncedSearch.cancel();
Two: running on the leading edge.
function debounce(fn, delay, { leading = false } = {}) {
let timerId = null;
return function (...args) {
const callNow = leading && timerId === null;
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = null;
if (!leading) {
fn.apply(this, args);
}
}, delay);
if (callNow) {
fn.apply(this, args);
}
};
}
The default waits for the burst to end, which is right for a search box. Leading edge fires immediately and then ignores the rest of the burst, which is right for a submit button you do not want double-clicked.
Three: getting a result back.
function debouncePromise(fn, delay) {
let timerId = null;
return function (...args) {
clearTimeout(timerId);
return new Promise((resolve, reject) => {
timerId = setTimeout(() => {
Promise.resolve(fn.apply(this, args)).then(resolve, reject);
}, delay);
});
};
}
The plain version returns undefined, because the real call happens later and there is nothing to return yet. This version returns a promise per call. Note that cancelled calls leave their promises pending forever, which is a real trade: for a search box nobody awaits the abandoned ones, but in other code that is a leak.
And the one people forget: this does not cancel work already started.
const debouncedSearch = debounce(async (term) => {
const results = await fetch(`/search?q=${term}`);
render(await results.json());
}, 300);
Debouncing stops extra requests from starting. Once one is in flight, a later one can still finish first and render stale results. That needs AbortController, which is a different problem wearing the same clothes.
Pro Tip: In an interview, write the eight-line version first and say out loud that you would add
cancelin real code. That sequence demonstrates you know the core mechanism and that you have used it in anger, which is more convincing than producing a fully featured version immediately.
EXERCISE
3Testing Something That Waits
A function whose whole behaviour is about timing needs tests that control time rather than wait for it.
The obvious test is to call the debounced function and wait. It works, it makes the suite slow, and it becomes flaky on a loaded machine.
The naive version:
test("debounce runs once", async () => {
let calls = 0;
const fn = debounce(() => { calls += 1; }, 300);
fn();
fn();
fn();
await new Promise((r) => setTimeout(r, 400));
expect(calls).toBe(1);
});
400 milliseconds of real waiting for one assertion. Twenty such tests is eight seconds, and any of them can fail on a slow CI runner because 400ms was not quite enough.
Fake timers, which most test runners provide:
test("debounce runs once", () => {
vi.useFakeTimers();
let calls = 0;
const fn = debounce(() => { calls += 1; }, 300);
fn();
fn();
fn();
expect(calls).toBe(0); // nothing yet
vi.advanceTimersByTime(300);
expect(calls).toBe(1);
vi.useRealTimers();
});
setTimeout is replaced with a controllable version, so advancing time is instant and exact. The test now also asserts something the slow version could not: that nothing ran before the delay, which is half the behaviour.
Which lets you test the parts that matter:
test("each call cancels the previous", () => {
vi.useFakeTimers();
const seen = [];
const fn = debounce((v) => seen.push(v), 300);
fn("a");
vi.advanceTimersByTime(100);
fn("b");
vi.advanceTimersByTime(100);
fn("c");
vi.advanceTimersByTime(300);
expect(seen).toEqual(["c"]);
});
test("cancel prevents the pending call", () => {
vi.useFakeTimers();
let calls = 0;
const fn = debounce(() => { calls += 1; }, 300);
fn();
fn.cancel();
vi.advanceTimersByTime(1000);
expect(calls).toBe(0);
});
There is a second reason to prefer fake timers that is easy to miss. The slow test can only check the end state, so it passes whether the function ran once at 300ms or ten times at 30ms intervals. Controlling the clock lets you assert at each step, which means the test is checking the behaviour rather than the outcome.
And a caveat worth knowing:
// Fake timers replace setTimeout, setInterval and often Date.now.
// Code that awaits a real network call, or a library that captured
// setTimeout before the fakes were installed, will not be affected.
// Install them before creating anything that schedules.
The general principle applies well beyond debounce. Anything whose behaviour is defined by time should take time as something it can be given rather than something it reads from the environment, and fake timers are the test-side version of that idea.
