Implement debounce(fn, wait). It returns a new function that waits until wait ms have passed since its last call. Then it calls fn once.
- Every call restarts the wait.
fngets the arguments andthisof the last call.- The debounced function returns nothing.
The returned function also has two methods. Here, the pending call is the call that is waiting for the timer.
cancel()drops the pending call, if there is one. Later calls work normally.flush()runs the pending call now, with the latest arguments andthis. It also clears the timer, so the call doesn't run again later. If nothing is pending,flush()does nothing.
Input: const d = debounce(save, 100);
d('a'); d('b'); // 100 ms pass
Output: save('b') is called once
Input: d('x'); d.flush();
Output: save('x') runs immediately; nothing runs at 100 ms
Input: d('y'); d.cancel(); // 100 ms pass
Output: save is not called