Skip to content
SDETRole
SDETRole

Debounce with cancel

advanced Timers Challenge 16 of 18

Write debounce(fn, wait). It returns a function that delays calling fn until wait ms have passed without another call. The returned function also has a cancel() method.

Requirements

  • Never call fn synchronously.
  • A burst of calls closer together than wait results in exactly one call to fn, wait ms after the last call, with the last call’s arguments.
  • Calls separated by more than wait produce separate calls.
  • debounced.cancel() drops any pending call.
  • Forward this to fn.

Expected output

const search = debounce(fn, 50); search('p'); search('pl'); search('play'); → fn is called once, about 50ms after the last call, with 'play'

Test cases (6)

  • ○does not call fn synchronously
  • ○collapses a burst into one call with the latest arguments
  • ○waits for a quiet period after the last call
  • ○separate bursts produce separate calls
  • ○cancel prevents the pending call
  • ○preserves this
solution.jsExecutes in your browser

Ctrl/⌘ + Enter to run tests · your code is saved in this browser

Results

Run the tests to see results here.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →