Difference between debounce and throttle? Implement both.
Coding-round standard. Tests whether you can wield closures AND understand UX trade-offs between "last signal wins" and "rate limit".
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.
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.
Debounce implementation: closure holds timerId, each call clears and sets a new timer.
Throttle implementation: closure holds lastCallTime, call fires only if now - last >= interval.
Edge cases: leading vs trailing invocation, cancel method for cleanup, max-wait for debounce (run at least every max ms).
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).
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.
If the component unmounts before the timer fires, yes. Return a cancel method and call it in cleanup to avoid stale updates.
debounceTime and throttleTime operators. Same semantics as lodash's _.debounce/_.throttle.
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