06 · Frontend Coding Patterns
easycodingjavascript~10 min

Implement debounce

Objective: Control timer lifecycles and preserve `this` and arguments.

Write `debounce(fn, wait)`. The wrapped function delays calling `fn` until `wait` ms have passed without another call, using the latest arguments.

  • Each call resets the timer.
  • `fn` receives the arguments (and `this`) of the last call.
  • The returned function has a `cancel()` method that drops a pending call.
JavaScript

⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • How does throttle differ from debounce, and when do you want each?
  • What would a leading-edge option change?
  • Why debounce a search request but throttle a scroll handler?