Skip to the page

Polyfills interviewers ask · core

Debounce (with leading, trailing, cancel and flush)

Debounce delays calling a function until it has not been called for wait ms — every call clears the previous timer and starts a new one — with options for a leading call, a trailing call, cancel() and flush().

The notes

What you must know

  • Core: let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), wait); }. The returned wrapper is a normal function so the caller's this is kept.
  • leading: call at once if no timer is active, then ignore calls until it has been quiet for wait. trailing: call after the quiet period with the last arguments. With both, the trailing call happens only if there were more calls during the wait.
  • cancel() clears the timer and the pending arguments. flush() runs the pending call now.
  • maxWait (lodash) forces a call at least every maxWait ms, making it behave like throttle during long bursts.
  • Uses: search input, resize end, autosave, validation after typing stops. Debounce does not fix response ordering.
  • In React, create the debounced function once (useMemo or useRef) and cancel it on unmount, or debounce the value instead.

The red pen

Common traps: mistake → fix

  • Mistake: Not clearing the previous timer

    Fix: every call fires later (a Tata 1mg candidate was rejected for this).

  • Mistake: An arrow wrapper loses this; creating a new debounced function on every render resets it.

  • Mistake: Mixing it up with throttle.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement debounce(fn, wait).
  2. Keep this and the arguments.
  3. Add leading and trailing options.
  4. Add cancel() and flush().
  5. Use it in a React search box. Why doesn't it fix out-of-order responses?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview