Implement a debounce function

A debounce wrapper keeps a timer in a closure; each call clears the previous timer and starts a new one, so the wrapped function runs only after wait ms without further calls, using the latest arguments and this.

Requirements to cover in an interview

  1. Trailing call with the latest arguments after the quiet period.
  2. Preserve this so it works as a method (use a regular function and fn.apply(this, args)).
  3. cancel() to drop a pending call (e.g. on component unmount).
  4. flush() to run the pending call immediately (e.g. save before leaving the page).
  5. Optional leading edge: run on the first call of a burst.
  6. Optional maxWait: guarantee a call at least every maxWait ms during long bursts.
  7. Return the result of the last invocation (Lodash does) or a promise, if needed.

Common mistakes

  • Creating a new debounced function on every render in React, so nothing is ever debounced. Create it once (useMemo/useRef) and cancel it in cleanup.
  • Using an arrow function for the wrapper, which loses the caller's this.
  • Forgetting that responses from debounced searches can still arrive out of order; abort stale requests.

Testing

Use fake timers (vi.useFakeTimers() / jest.useFakeTimers()) and advance time instead of waiting.

Code example

js
1function debounce(fn, wait, { leading = false, maxWait } = {}) {
2 let timer = null, maxTimer = null, lastArgs, lastThis, result;
3
4 const invoke = () => {
5 clearTimeout(timer);
6 clearTimeout(maxTimer);
7 timer = maxTimer = null;
8 if (lastArgs) {
9 result = fn.apply(lastThis, lastArgs);
10 lastArgs = lastThis = undefined;
11 }
12 return result;
13 };
14
15 function debounced(...args) {
16 const isFirstInBurst = timer === null;
17 lastArgs = args;
18 lastThis = this; // keep the caller's `this`
19 if (isFirstInBurst && leading) {
20 result = fn.apply(this, args);
21 lastArgs = undefined; // already handled
22 }
23 clearTimeout(timer);
24 timer = setTimeout(invoke, wait);
25 if (maxWait != null && maxTimer === null) maxTimer = setTimeout(invoke, maxWait);
26 return result;
27 }
28 debounced.cancel = () => {
29 clearTimeout(timer);
30 clearTimeout(maxTimer);
31 timer = maxTimer = null;
32 lastArgs = lastThis = undefined;
33 };
34 debounced.flush = () => invoke();
35 return debounced;
36}
37
38const calls = [];
39const search = debounce((q) => calls.push(q), 50);
40["a", "ab", "abc"].forEach((q) => search(q));
41await new Promise((r) => setTimeout(r, 80));
42console.log(calls); // ["abc"]
43
44// `this` is preserved for methods
45const editor = { text: "draft", save: debounce(function () { calls.push(`saved ${this.text}`); }, 20) };
46editor.save();
47editor.save.flush(); // run now
48console.log(calls.at(-1)); // saved draft
49
50// cancel drops the pending call
51search("never");
52search.cancel();
53await new Promise((r) => setTimeout(r, 80));
54console.log(calls.includes("never")); // false
55
56// maxWait: a call is guaranteed during a long burst
57const progress = [];
58const autosave = debounce((n) => progress.push(n), 40, { maxWait: 100 });
59for (let i = 0; i < 20; i++) setTimeout(() => autosave(i), i * 15); // a 300ms burst
60await new Promise((r) => setTimeout(r, 400));
61console.log(progress.length > 1, progress.at(-1)); // true 19 - saved during the burst and at the end

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app