Skip to main content
01

Implement debounce

Mediumclosurestimersthis

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Implement debounce(func, wait). It returns a new function that delays calling func until wait milliseconds have passed since the last time the debounced function was called.

Debouncing is how you stop a search box from sending a request on every keystroke, or a resize handler from running hundreds of times a second: only the final call in a burst gets through.

js
let i = 0
const increment = () => i++
const debounced = debounce(increment, 100)

// t = 0
debounced()
// i is still 0

// t = 50: a new call restarts the 100ms wait
debounced()

// t = 150: 100ms have passed since the last call
// i is now 1

Requirements

  • debounce returns a function, and calling it does not call func right away.
  • func is called once, wait ms after the most recent call. Every new call restarts the wait.
  • func receives the arguments of the latest call.
  • func runs with the same this the debounced function was called with.
  • Each debounced function has its own timer.

Note

You don't need to support the leading, maxWait or cancel options that Lodash's debounce has.

Approach

The debounced function needs to remember one thing between calls: the pending timer. A closure gives each debounced function its own private timeoutId.

On every call:

  1. Cancel the pending timer with clearTimeout, if there is one. This is what "restarts the wait".
  2. Start a new timer for wait ms that calls func.

Because only the last timer survives a burst, func runs once, with the arguments of the last call.

Keeping this and the arguments

Two details are easy to get wrong:

  • Arguments: collect them with rest parameters (...args) and pass them on with func.apply.
  • this: the debounced function must be a regular function, not an arrow function, so it receives the caller's this. The timer callback, on the other hand, should be an arrow function, so it captures that this lexically. With a regular callback, this inside it would be undefined (or globalThis).
Loading diagram...

Complexity

Each call is O(1) time. Memory is O(1) per debounced function: one timer id plus the latest arguments held by the pending callback.

Follow-ups interviewers ask

  • cancel() and flush(): attach methods to the returned function that clear the timer, or run the pending call right away.
  • Leading edge: call func on the first call of a burst instead of the last.
  • Debounce vs. throttle: throttle guarantees at most one call per interval during a burst; debounce waits for the burst to end.

Reference solution

js
/**
 * @param {Function} func
 * @param {number} wait
 * @returns {Function}
 */
export default function debounce(func, wait) {
  let timeoutId = null

  return function debounced(...args) {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      timeoutId = null
      func.apply(this, args)
    }, wait)
  }
}
ts
export default function debounce<Args extends unknown[]>(
  func: (this: unknown, ...args: Args) => void,
  wait: number,
): (this: unknown, ...args: Args) => void {
  let timeoutId: ReturnType<typeof setTimeout> | undefined

  return function debounced(this: unknown, ...args: Args) {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      timeoutId = undefined
      func.apply(this, args)
    }, wait)
  }
}