coding round · ~15 min
JavaScriptintermediate

Implement debounce

Write debounce(fn, wait) that returns a debounced version of fn: it waits until wait ms have passed since the last call, then calls fn once with the latest arguments and the latest this. Nothing runs right away (there is no leading call).

  • d(1); d(2); d(3) in quick succession → fn(3) runs once, wait ms after the last call
  • with wait = 60: d('a'), then d('b') 30ms later → only fn('b') runs, at about 90ms
  • obj.save = debounce(fn, 100); obj.save(1) → fn is called with this === obj
  • d(); d.cancel() → fn never runs

The returned function must also have a cancel() method that drops any pending call. After a cancel, or after a call has fired, the debounced function keeps working as normal.

Define debounce in the editor. 6 tests will call it.

read the related note →

solution.js
function debounce(fn, wait) {
  // Return a function that calls fn only after `wait` ms
  // have passed without another call, using the latest arguments and `this`.
  // The returned function also needs a .cancel() method.
}

Tests⌘/Ctrl + Enter to run

does not call fn right away
collapses a burst of calls into one call with the last arguments
restarts the timer on every call
preserves this and passes every argument
cancel() drops the pending call
keeps working after cancel() and after firing
esc