Skip to content
Onsite

Debounce

MediumP1Coding

Implement debounce(fn, wait).

It returns a new function. Each call to it restarts a timer of wait milliseconds. fn runs only when the timer finishes without another call, and it receives the arguments and this of the last call.

Also add a cancel() method on the returned function that clears any pending call.

Example 1

Input
const d = debounce(log, 100); d('a'); d('b'); d('c');
Output
log('c') runs once, 100 ms after the last call
Why
Each call restarts the timer, so only the last one survives.

Constraints

  • 0 <= wait <= 10^4
  • Use setTimeout and clearTimeout; do not use a library.

Hints

Run checks the 3 visible tests, Submit all 6.