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
fnsynchronously. - A burst of calls closer together than
waitresults in exactly one call tofn,waitms after the last call, with the last call’s arguments. - Calls separated by more than
waitproduce separate calls. debounced.cancel()drops any pending call.- Forward
thistofn.
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.