← Questions

Implement a debounce function with a wait time

0
AppleCodingLast asked Feb 2026

Write debounce(fn, wait). It returns a new function that delays calling fn until wait milliseconds have passed without another call. When fn finally runs, it gets the arguments and the this of the most recent call.

Interface

Unless you agree on a different interface with the interviewer, assume (JavaScript):

  • debounce(fn, wait) -> debounced: each call to debounced(...args) restarts the timer.
  • debounced.cancel(): drops a pending call.

Example

With wait = 100:

t=0    debounced("a")
t=50   debounced("b")     # restarts the timer
t=120  debounced("c")     # restarts the timer
t=220  fn("c") runs       # 100 ms after the last call
t=300  debounced("d")
t=400  fn("d") runs

Constraints

  • No libraries; use setTimeout and clearTimeout.
  • this must be preserved when the debounced function is used as a method.

Clarifying questions

  • Should the call fire at the end of the quiet period (trailing), at the start (leading), or both?
  • Does the debounced function need to return a value, or a promise?
  • Do we need cancel or flush?

What a strong answer covers

  • A closure holding the timer ID, the last arguments and the last this.
  • Why an arrow function or fn.apply(this, args) is needed to keep this.
  • The difference from throttle.
  • Tests with fake timers: rapid calls fire once, separated calls fire each time, cancel stops a pending call.

Follow-ups

  • Add a leading option: with leading only, the example above calls fn("a") at t=0 and fn("d") at t=300.
  • Add flush() to run a pending call immediately.
  • Add maxWait so a steady stream of calls still fires at least that often.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding