Build a Quiet-Period Call Delayer in JavaScript
Data Structure DesignModel answerLast updated
Write a higher-order function that postpones a callback until calls have stopped for a given time, preserving this and arguments, and discuss cancel, flush and leading-edge variants.
Delay Until Calls Go Quiet
Write a function debounce(func, delay) that wraps func and returns a new function. The wrapper must not run func right away. Instead, func should run only once the wrapper has gone delay milliseconds without being called. Every new call to the wrapper during that waiting period discards the pending run and restarts the countdown.
Requirements
- The wrapper must preserve the
thisvalue it was called with, so it works when attached to an object as a method. - Every argument given to the wrapper must be passed on to
func. - When several calls happen in quick succession,
funcmust run only once, using the context and arguments of the final call.
Signature
/**
* @param {Function} func - The function to wrap.
* @param {number} delay - Quiet period in milliseconds.
* @return {Function} - The wrapped function.
*/
function debounce(func, delay) {
// your implementation
}
Example
const greet = debounce(() => console.log('Hello!'), 1000);
greet();
greet();
// 'Hello!' is printed once, about 1000 ms after the second call.
Constraints
delayis a non-negative integer.funcmay be an anonymous function or a method that belongs to an object.
Things to address in your answer
- What should the wrapper return, given that
funcruns later? Explain the trade-off. - Show that a burst of rapid calls cannot cause more than one execution.
- Describe how you would extend the design (for example cancelling, flushing, or running on the leading edge).
Explain your approach, state the time and space complexity, and give the code.
Hints
Hint 1
You need state that survives between calls but is private to each wrapped function. Think about what a closure can hold, and what handle you get back when you schedule a timer.
Hint 2
Before scheduling a new run, cancel the one that is already pending. That guarantees at most one live timer at any moment.
Hint 3
Pay attention to which kind of function you use at each level. The returned wrapper needs its own dynamic `this`, while the timer callback needs to reuse the wrapper's `this` and arguments. Rest parameters plus `apply` handle forwarding.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This pattern is a closure around a cancellable timer. debounce creates one private variable, timerId, and returns a wrapper that shares it across all of its calls. Each call of the wrapper does three things:
- Cancels any pending timer with
clearTimeout(timerId). - Schedules a new timer for
delayms. - Records the current
thisand arguments so the delayed call uses them.
The countdown restarts on every call, so func runs only after the caller has been silent for delay ms. This is called trailing-edge execution, and it uses the latest call's context and arguments.
Implementation
function debounce(func, delay) {
let timerId = null;
return function debounced(...args) {
clearTimeout(timerId); // drop the pending run, if any
timerId = setTimeout(() => { // arrow fn keeps the wrapper's `this`
timerId = null;
func.apply(this, args);
}, delay);
};
}
Why it works
- One run per burst. Every call clears the previous timer before creating a new one, so at most one timer is pending. After N rapid calls only the last timer is alive.
- Correct timing. The surviving timer was created at the last call, so it fires
delayms after that call. thishandling. The returned wrapper is a regularfunction, sothisis determined by the call site (for exampleobj.method()). The timer callback is an arrow function, so it captures that samethislexically. A plainfunctionthere would lose it (undefinedin strict mode, otherwise the global object).- Arguments.
...argscollects them, andapplyspreads them intofunc. - Independent instances. Each
debounce(...)call creates its own closure and timer, so different debounced functions never interfere.
Complexity
- Time: O(1) per wrapper call (one clear, one schedule). The eventual run costs whatever
funccosts. - Space: O(1) per debounced function: one timer handle plus the latest
thisand arguments.
Edge cases and trade-offs
- Return value. The real call is asynchronous, so the wrapper cannot synchronously return
func's result. It returnsundefined. If the caller needs the result, return a Promise that resolves whenfunceventually runs. The catch is that earlier calls whose runs were discarded need a defined outcome too (resolve with the final result, or reject/ignore), which complicates the contract. Stating this explicitly is better than silently ignoring it. delay = 0.funcstill runs asynchronously on a later macrotask. Calls made in the same synchronous block still collapse into one run.- Method use.
obj.save = debounce(obj.save, 300)works becausethisis resolved at call time. Calling a detached wrapper bare gives the samethisthe original would have received when called bare. - Memory. Setting
timerId = nullafter firing keeps state clean. Holding on to oldthis/argsafter a run can retain objects longer than needed, so clear them if you store them separately.
Polished version with cancel and flush
function debounce(func, delay) {
let timerId = null;
let lastThis, lastArgs;
function debounced(...args) {
lastThis = this;
lastArgs = args;
clearTimeout(timerId);
timerId = setTimeout(invoke, delay);
}
function invoke() {
timerId = null;
const ctx = lastThis, a = lastArgs;
lastThis = lastArgs = undefined;
func.apply(ctx, a);
}
debounced.cancel = () => {
clearTimeout(timerId);
timerId = null;
lastThis = lastArgs = undefined;
};
debounced.flush = () => {
if (timerId !== null) {
clearTimeout(timerId);
invoke();
}
};
return debounced;
}
cancel is useful when a UI component unmounts. flush is useful before navigation, for instance to save a pending draft immediately.
Common mistakes
- Creating the timer variable inside the returned function, so it resets on every call and nothing is ever cancelled.
- Forgetting to clear the old timer, which produces one run per call, just delayed.
- Using an arrow function for the returned wrapper, which loses the caller's
this. - Using a plain
functionas the timer callback, which losesthisandargs. - Calling
func(args)instead offunc(...args)orapply, which passes an array instead of separate arguments.
Follow-ups
Leading-edge mode. Run func immediately if no timer is pending, then use the timer only to reopen the gate after delay ms of silence.
function debounce(func, delay, immediate = false) {
let timerId = null;
return function (...args) {
const callNow = immediate && timerId === null;
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = null;
if (!immediate) func.apply(this, args);
}, delay);
if (callNow) func.apply(this, args);
};
}
Libraries commonly support both edges together through leading and trailing options.
Debounce versus throttle. Debounce waits for silence, which suits search-as-you-type or autosave. Throttle guarantees at most one run per interval, which suits scroll handlers or continuous progress updates.
Animation-frame variant. For visual work, replace the timer with requestAnimationFrame/cancelAnimationFrame so that all calls within one frame collapse into one run just before paint. That behaves more like per-frame coalescing than a true time-based quiet period.
Maximum wait. To prevent starvation under a constant stream of calls, add a maxWait option that forces a run if too much time has passed since the first call in the burst.