Frontend Interview Questions

Debounce vs Throttle: When to Use Which

Difference between debounce and throttle? Implement both.

Why Interviewers Ask This

Coding-round standard. Tests whether you can wield closures AND understand UX trade-offs between "last signal wins" and "rate limit".

How to Answer

  1. 1

    Debounce: delay execution until N ms have passed since the LAST call. If calls keep coming, function never fires. Use for: search-as-you-type (wait till user stops), window resize end.

  2. 2

    Throttle: execute at most once per N ms. First call fires immediately (or at interval end, depending on variant). Use for: scroll listeners, mousemove, rate-limited API polling.

  3. 3

    Debounce implementation: closure holds timerId, each call clears and sets a new timer.

  4. 4

    Throttle implementation: closure holds lastCallTime, call fires only if now - last >= interval.

  5. 5

    Edge cases: leading vs trailing invocation, cancel method for cleanup, max-wait for debounce (run at least every max ms).

Sample Answer

Debounce is 'wait for silence'; throttle is 'rate limit'. For a search box I debounce 300ms — no API call until the user pauses. For scroll-based animations or sticky-header logic I throttle to 16ms (~60fps) — I want steady updates during the gesture, not silence. Lodash has both, but rolling your own is a 10-line closure: debounce holds a timerId and resets it on every call, throttle holds a lastTime and only fires if enough time has passed. Options I usually expose: `leading` (fire immediately then cooldown), `trailing` (fire at the tail), `maxWait` for debounce (don't let it defer forever).

Pro Tips

  • requestAnimationFrame is a better "throttle to frame rate" than setTimeout — syncs to the render cycle.

  • For React: use useRef to hold the timer across renders; don't recreate the debounced function on each render.

  • HireMe AI (即答侠) has both implementations memorized so you can whiteboard them without fumbling closures.

Frequently Asked Questions

Can debounce miss the final call?

If the component unmounts before the timer fires, yes. Return a cancel method and call it in cleanup to avoid stale updates.

RxJS equivalents?

debounceTime and throttleTime operators. Same semantics as lodash's _.debounce/_.throttle.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free