← Whiteboard questions

Write a debounce function

Delay a call until the calls stop

Coding, Medium

Small real code that works when called late, twice, or with bad input.

Write debounce(fn, waitMs, options) in JavaScript (or the same idea in another language with timers). It returns a new function. Each call to the new function restarts a timer of waitMs. When a full waitMs passes with no new call, fn runs once with the arguments and this of the most recent call. The returned function also has cancel(), which stops a pending call. With { leading: true }, fn runs at the first call of a burst instead of at the end, and does not run again at the end of that burst.

Examples

Input wait = 50 ms. Calls at 0 (arg 1), 20 (arg 2), 40 (arg 3), then silence
Output fn(3) runs once at 90
Why 40 + 50. The calls before it are dropped.
Input wait = 50 ms. A call at 0, then silence; a second call at 200
Output fn runs at 50 and at 250
Why These are separate bursts.
Input wait = 50 ms, { leading: true }. Calls at 0 and 20; a call at 200
Output fn runs at 0 and at 200 only
Why The call at 200 is a new burst, so fn runs at 200.

Constraints

Your answer must contain

Target A strong answer covers the timer reset, the latest arguments and this, the leading option, cancel, and a test with a fake clock.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Think about what should happen when a call arrives while a timer is still waiting. What should the old timer do?

Hint 2 the approach

Keep one timer and the latest arguments. Every call clears the old timer and starts a new one, so the timer fires only after a full quiet period.

Hint 3 the key step

When the timer fires, run the function with the stored arguments and this. With leading, run at the first call of a burst. Cancel clears the timer.

Walkthrough

Full walkthrough brute force to best

Naive version

Start a new timer for every call and never clear the old ones. Every call in a burst then runs the function later, so ten fast calls give ten runs, and old arguments are used. That is the behaviour debounce exists to prevent.

Better version

Clear the old timer and start a new one on each call, and run the function with the arguments of that call. This gives the trailing behaviour. It loses this if you use an arrow function, and it has no cancel and no leading mode.

Best method

Keep three pieces of state: one timer id, the latest arguments and the latest this. Each call stores its arguments and this, clears the old timer and starts a new one for the wait time. When the timer fires, it runs the function with the stored arguments and this, and resets the timer id to null. With leading on, the call that finds no timer is the first of a burst: run the function at once, and skip the run at the end of that burst. Cancel clears the timer and sets it to null, so the next call starts a new burst. Use a normal function for the returned function, not an arrow function, so this is the caller.

Worked example

Run the first example with a wait of 50 ms. The call at 0 starts a timer for 50. The call at 20 clears it and starts one for 70. The call at 40 clears that one and starts one for 90, with argument 3 stored. Nothing else arrives, so the timer fires at 90 and the function runs once with 3.

Reference code

function debounce(fn, waitMs, { leading = false } = {}) {
  let timer = null, lastArgs, lastThis;
  function debounced(...args) {
    lastArgs = args; lastThis = this;
    const callNow = leading && timer === null;   // first call of a burst
    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = null;
      if (!leading) fn.apply(lastThis, lastArgs);
    }, waitMs);
    if (callNow) fn.apply(lastThis, lastArgs);
  }
  debounced.cancel = () => { clearTimeout(timer); timer = null; };
  return debounced;
}

Time and memory

O(1) time per call, because a call stores two values and resets one timer. O(1) memory for each debounced function.

Common mistakes

  • Not clearing the old timer. Several calls then run the function.
  • Keeping the arguments of the first call instead of the last.
  • Using an arrow function for the returned function. It loses the caller's this.
  • Running the function at both ends of a burst when only leading was asked for.

Related problems

Write a debounce function: walkthrough and Python solution