FrontendInterviews.dev

Loading problem…

60. Debounce Function

Easy•

Implement debounce - a utility that delays function execution until calls stop for a fixed time window.

Requirements

1) Input

  • Accept a function fn and a delay delay in milliseconds.
  • Return a function debounced(...args).

2) Trailing-edge behavior

  • Every call to debounced resets the timer.
  • Only the latest call in a burst should invoke fn.
  • Invoke fn after delay milliseconds using the latest arguments.

3) Context and arguments

  • When fn runs, preserve the caller's this value.
  • Forward all arguments from the latest call.

4) Zero-delay edge case

  • A delay of 0 must still schedule asynchronously (next macrotask).

Examples

const calls = []
const debounced = debounce((value) => calls.push(value), 30)

debounced("a")
debounced("b")
debounced("c")

// After ~30ms: calls is ["c"]
const obj = {
  base: 10,
  add: debounce(function (x) {
    this.result = this.base + x
  }, 20),
}

obj.add(5)

// After ~20ms: obj.result is 15
const order = []
const debounced = debounce(() => order.push("later"), 0)

order.push("start")
debounced()
order.push("end")

// After next task: order is ["start", "end", "later"]

Constraints

  • Reset any pending timeout on each call so only the latest invocation runs.
  • Invoke the original function with the latest call's `this` context and arguments.
  • Do not execute before the full delay window after the most recent call.
  • With delay 0, execution must remain asynchronous.
Accepted38/42|Acceptance Rate90.5%