Implement debounce() in JavaScript
debounce(fn, delay) by returning a trailing-edge wrapper that clears the previous timer and runs fn only after calls stop for delay ms. The wrapper must not call fn synchronously, must run only the latest call in a burst, and must pass that call's this and all of its arguments to fn.Arguments
fn: Function —The function to be executed after the delay. delay: number —The delay in milliseconds before executing the function.
Returns
Function — Solution idea
Interview answer: the base prompt is a trailing-edge debounce with one timeoutId; cancel(), flush(), and leading are follow-ups.
// Example: timeline with delay=100
const log = debounce((value) => console.log(value), 100)
log('A') // t=0
// t=50: log('B') resets the timer
// t=90: log('C') resets it again
// Only C runs at t=190
// Basic example
const sayHello = debounce(() => console.log('Hello!'), 300)
sayHello()
// Multiple rapid calls — only last one runs
const run = debounce(() => console.log('Run!'), 500)
run()
run()
run() // Only this one executes after 500ms
// With arguments
const greet = debounce(name => console.log(`Hi ${name}`), 400)
greet('Alice')
greet('Bob') // Only 'Hi Bob' logs after 400msPublic interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- PracHub: Waymo senior frontend engineer interview experience, May 2026
One self-reported senior loop describes an onsite exercise to build an autocomplete with debouncing. Debounce is the supporting primitive for that exercise, not the reported wording.
- LeetCode Discuss: Google front end engineer onsite, Sunnyvale, spring 2019
One Google onsite account describes an API that takes a function and a duration and runs the function after the interval, still waiting if called before the interval ends. Debounce is the closest primitive; it is not the reported wording.
- Blind: Google frontend interview questions thread, December 2020
The thread lists a Google prompt to return a version of a function that runs on a timeout. Debounce is a practice version of that shape; the thread is a compiled list, not one loop.
- Taro: Netflix senior frontend engineer interview, 2024
One senior Netflix account describes a search-input problem where the interviewer discussed a 200 millisecond debounce. This drill practises that primitive, not the reported exercise.
- LeetCode Discuss: Zalando senior frontend engineer interview, Berlin, July 2024
One senior account lists the solution-discussion question 'can you write your own debouncing method?' after a search-box take-home. This exercise is that utility in isolation; the reported round asked for it inside a larger discussion.
- enginebogie: Booking.com frontend engineer machine-coding round, May 2023
One account lists debounce or throttle as a required part of a 60-minute typeahead machine-coding round. This exercise practises the utility on its own; the reported round asked for it inside a larger component.
Reported in a public Waymo interview account. Waymo frontend interview questions
Reported in a public Google interview account. Google frontend interview questions
Reported in a public Netflix interview account. Netflix frontend interview questions
Reported in a public Zalando interview account. Zalando frontend interview questions
Reported in a public Booking.com interview account. Booking.com frontend interview questions
Solution
Overview
Interview answer: the base prompt is a trailing-edge debounce with one timeoutId; cancel(), flush(), and leading are follow-ups.
Goal: ensure fn runs only after calls have stopped for delay ms. This is common for search inputs, resize/scroll handlers, and deduping rapid UI events. Approaches 2 and 3 show common extensions used in real-world libraries.
Approach 1: Timeout-based debounce (canonical)
Idea: store a timeoutId. Each call clears the previous timeout and schedules a new one. When the last timer completes, invoke fn with the latest args and this.
How it works:
- Keep
let timeoutIdin the closure. - On each call, clear any existing timer with
clearTimeout(timeoutId). - Start a new timer:
timeoutId = setTimeout(() => fn.apply(this, args), delay). - Return the debounced wrapper function.
This is the classic trailing-edge debounce: only the last call in a burst actually runs.
export default function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
}
export default function debounce<F extends (...a: any[]) => void>(fn: F, delay: number): F {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
return function (this: any, ...args: Parameters<F>) {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => fn.apply(this, args), delay);
} as F;
}
Approach 2: Debounce with cancel + flush helpers (extended API)
Idea: extend the basic debounced function with .cancel() and .flush() helpers so callers can cancel a pending call or force it to run immediately.
How it works:
- Wrap the debounced function and keep
timeoutId,lastArgs, andlastThisin the closure. - On each call, store the latest args/context, clear the previous timer, and start a new one.
.cancel()just clears the timer..flush()clears the timer and immediately invokesfnwith the last stored args and context.
This pattern mirrors popular utility libraries (like Lodash) and is an extension beyond the minimal debounce(fn, delay) contract.
export default function debounce(fn, delay) {
let timeoutId, lastArgs, lastThis;
function debounced(...args) {
lastArgs = args;
lastThis = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = undefined;
fn.apply(lastThis, lastArgs);
}, delay);
}
debounced.cancel = () => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
};
debounced.flush = () => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
timeoutId = undefined;
fn.apply(lastThis, lastArgs);
}
};
return debounced;
}
type Debounced<F extends (...a: any[]) => void> = F & { cancel: () => void; flush: () => void };
export default function debounce<F extends (...a: any[]) => void>(fn: F, delay: number): Debounced<F> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let lastArgs: Parameters<F>;
let lastThis: any;
const debounced = function (this: any, ...args: Parameters<F>) {
lastArgs = args;
lastThis = this;
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
timeoutId = undefined;
fn.apply(lastThis, lastArgs);
}, delay);
} as Debounced<F>;
debounced.cancel = () => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
};
debounced.flush = () => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
timeoutId = undefined;
fn.apply(lastThis, lastArgs);
}
};
return debounced;
}
Approach 3: Leading-edge option (extended signature)
Idea: add an options object to support leading mode. With leading: true, call fn immediately on the first trigger in a burst and then suppress further calls until the delay elapses. With leading: false (default), fall back to classic trailing-only debounce.
How it works:
- Track
timeoutId, plus the last arguments andthis. - On each call, compute
shouldCallNow = leading && !timeoutIdto know whether this should be an immediate (leading) call. - Clear any existing timer and start a new one. In trailing mode (
leading === false), the timer will callfnafterdelaywith the last arguments. In leading mode, the timer simply resetstimeoutIdafterdelayso that a new burst can trigger another leading call. - If
shouldCallNowis true, invokefnimmediately with the current arguments.
This is an API extension: the base exercise only requires debounce(fn, delay), but this shows how to evolve it to support configurable leading behavior.
export default function debounce(fn, delay, { leading = false } = {}) {
let timeoutId, lastArgs, lastThis;
return function (...args) {
lastArgs = args;
lastThis = this;
const shouldCallNow = leading && !timeoutId;
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
timeoutId = undefined;
if (!leading) {
fn.apply(lastThis, lastArgs);
}
}, delay);
if (shouldCallNow) {
fn.apply(lastThis, lastArgs);
}
};
}
export default function debounce<F extends (...a: any[]) => void>(
fn: F,
delay: number,
opts: { leading?: boolean } = {}
): F {
const { leading = false } = opts;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let lastArgs: Parameters<F>;
let lastThis: any;
const debounced = function (this: any, ...args: Parameters<F>) {
lastArgs = args;
lastThis = this;
const shouldCallNow = leading && !timeoutId;
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
timeoutId = undefined;
if (!leading) {
fn.apply(lastThis, lastArgs);
}
}, delay);
if (shouldCallNow) {
fn.apply(lastThis, lastArgs);
}
} as F;
return debounced;
}
Notes & Pitfalls
Return value is usually lost; debounced wrappers typically return void. If you need a result, consider callbacks or promises.Be careful with this— usefn.apply(this, args)(orfn.call) so methods still see the correct context.Timers differ between environments (Node vs browser), but setTimeout/clearTimeoutwork in both.
delay = 0 → effectively batches multiple calls into one at the end of the event loop. Rapid continuous calls → only the last invocation executes after inactivity in trailing mode. In long-lived components, remember to cancel timers (e.g. via .cancel()) on unmount to avoid stray executions.
Using closures to store timer and last-arguments state. Clearing and resetting timeouts to restart the debounce window. Extending the basic pattern with cancel/flush helpers and leading-edge options.
Common mistakes on this challenge
Debounce should wait for the trailing timer
The base debounce contract schedules work after the delay instead of calling fnin the wrapper body.Return a wrapper function and schedule fninsidesetTimeout.Do not call fnbefore the timer callback runs.Check that the calls array is still empty immediately after invoking the debounced function.
Latest call is not winning the debounce window
Rapid calls should cancel previous timers so only the latest invocation runs after the final delay. Store timer id in closure scope and clearTimeout(timer)before scheduling a new one.Assign timer = setTimeout(...)on every call.Validate with A -> B -> C calls: execution should remain empty until C has waited the full delay.
Debounced callback is losing args or context
The delayed invocation should keep both call arguments and thisbinding.Return a regular function wrapper (not arrow) if thismust be preserved.Inside timeout use fn.apply(this, args).Keep the thisand the wholeargsarray of every call, so the call that fires is the last one, with all of its arguments.Confirm context-based examples like search-box:reactstill pass after the delay.
Common interview follow-ups:
How would you add .cancel()so pending work can be cleared on unmount?How would you add .flush()so the latest pending call runs immediately?How would the implementation change for leading-edge debounce?
Resources
Related links
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.