JavaScript interview: Implement debounce

medium
closures
timers

Write debounce(fn, wait). It returns a new function. Every call restarts a wait ms timer, and fn only runs when the timer finishes, with the arguments of the last call.

Keep this from the last call, and add a cancel() method that drops a pending call.

Your code

Runs in a Web Worker in your browser. Tests use real timers, so a run takes a second or two.

FAQ