Write a debounce function
Coding, Medium
Small real code that works when called late, twice, or with bad input.
Write debounce(fn, waitMs, options) in JavaScript (or the same idea in another language with timers). It returns a new function. Each call to the new function restarts a timer of waitMs. When a full waitMs passes with no new call, fn runs once with the arguments and this of the most recent call. The returned function also has cancel(), which stops a pending call. With { leading: true }, fn runs at the first call of a burst instead of at the end, and does not run again at the end of that burst.
Examples
Input wait = 50 ms. Calls at 0 (arg 1), 20 (arg 2), 40 (arg 3), then silence
Output fn(3) runs once at 90
Why 40 + 50. The calls before it are dropped.
Input wait = 50 ms. A call at 0, then silence; a second call at 200
Output fn runs at 50 and at 250
Why These are separate bursts.
Input wait = 50 ms, { leading: true }. Calls at 0 and 20; a call at 200
Output fn runs at 0 and at 200 only
Why The call at 200 is a new burst, so fn runs at 200.
Constraints
waitMsis a number >= 0.fnmay be called with any arguments and anythis.cancel()may be called when nothing is pending, and must be safe then.
Your answer must contain
- The code; what state it keeps and why; what happens on cancel and on leading; how you would test it without waiting in real time; one sentence on how throttle is different.