JavaScriptMedium
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
- Trailing call with the latest arguments after the quiet period.
- Preserve
thisso it works as a method (use a regular function andfn.apply(this, args)). cancel()to drop a pending call (e.g. on component unmount).flush()to run the pending call immediately (e.g. save before leaving the page).- Optional
leadingedge: run on the first call of a burst. - Optional
maxWait: guarantee a call at least everymaxWaitms during long bursts. - 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;34 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 };1415 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 handled22 }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}3738const 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"]4344// `this` is preserved for methods45const editor = { text: "draft", save: debounce(function () { calls.push(`saved ${this.text}`); }, 20) };46editor.save();47editor.save.flush(); // run now48console.log(calls.at(-1)); // saved draft4950// cancel drops the pending call51search("never");52search.cancel();53await new Promise((r) => setTimeout(r, 80));54console.log(calls.includes("never")); // false5556// maxWait: a call is guaranteed during a long burst57const 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 burst60await 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.