← Questions
Implement a debounce function with a wait time
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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 todebounced(...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
setTimeoutandclearTimeout. -
thismust 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
cancelorflush?
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 keepthis. - The difference from throttle.
- Tests with fake timers: rapid calls fire once, separated calls fire each time,
cancelstops a pending call.
Follow-ups
- Add a
leadingoption: with leading only, the example above callsfn("a")at t=0 andfn("d")at t=300. - Add
flush()to run a pending call immediately. - Add
maxWaitso a steady stream of calls still fires at least that often.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
