QuestionsJavaScript

Implement debounce

Implement from scratchMediumJavaScript

Write debounce(fn, delay): return a function that delays calling fn until `delay` ms have passed since the LAST call.

What it tests

Closures + timer management. The #1 asked utility. Know debounce vs throttle cold.

Approach & answer

Keep a timer id in the closure. Every call clears the pending timer and schedules a new one, so fn only fires once the calls stop for `delay` ms. Preserve `this` and args by using a regular function and fn.apply. Debounce = 'wait for quiet' (search input, resize). Throttle = 'at most once per interval' (scroll, mousemove). Interview-grade extensions to mention: a leading-edge option that fires immediately on the first call then suppresses the trailing one; and a cancel()/flush() method (attach them to the returned function) so callers can abort a pending call on unmount or force it to run now. In React, wrap the debounced function in useMemo/useRef so a new debounced instance isn't created every render (which would reset the timer and defeat the whole thing).

Use this technique when

Search-as-you-type, autosave, resize/scroll handlers — anywhere rapid events should collapse into one action.

References

js