15.2. Debounce with leading edge, maxWait, cancel and flush
Topics
This question is in
15. Debounce and throttleA plain debounce waits until the calls stop. Real code needs more control. A "Send" button should act on the first click and ignore the double-click that follows. An autosave that waits for typing to stop must still save every few seconds for someone who never stops. A form that closes must be able to cancel a waiting save, or flush it so it happens now. The debounce in utility libraries offers all of this, and this problem rebuilds it, with the same behavior as lodash's debounce.
Write debounce(fn, wait, options) in debounce.js.
Signature
function debounce(fn, wait = 0, options = {}) // returns a debounced function
debounced(...args) // returns the result of fn's most recent run
debounced.cancel() // drops the waiting call and forgets the burst
debounced.flush() // ends the burst now; returns the latest result
debounced.pending() // true while a burst is in progressoptions.leading(defaultfalse): runfnat the first call of a burst.options.trailing(defaulttrue): runfnwhen the burst ends.options.maxWait(default: none): never delayfnlonger than this during a burst.
A burst is a series of calls, each less than wait ms after the one before. It ends when wait ms pass with no call. When fn runs, it always gets the this and the arguments of the latest call.
Requirements
- With no options it is a plain debounce:
fnruns once,waitms after the last call of a burst. - Every call returns the result of
fn's most recent run, orundefinedif it has not run yet. leading: true: the first call of a burst runsfnat once, and that call returns the new result. Later calls in the same burst do not run it at once.- The trailing run at the end of a burst happens only when
trailingis true and a call came afterfnlast ran. So withleadingandtrailingboth on, a single call runsfnonce, and a burst of several calls runs it twice. leading: true, trailing: falserunsfnonce per burst. With both off,fnnever runs.maxWait: during a long burst, oncemaxWaitms have passed sincefnlast ran (or since the burst began),fnruns with the latest call. AmaxWaitsmaller thanwaitcounts aswait. Without the option, there is no such limit.cancel()stops the timer, drops the waiting call and forgets the burst, so the next call starts a new one (and runs at once withleading). It is harmless when nothing waits.flush(), during a burst, ends it now: iftrailingis on and a call is waiting,fnruns at once with it. Nothing runs later for that burst.flush()returns the latest result; with no burst in progress it just returns that result.pending()is true from the call that starts a burst until the burst ends, is flushed or is cancelled.- Each debounced function has its own state. With
wait0 and noleading,fnstill runs in a later timer, never during the call. A non-functionfnthrows aTypeError.
Examples
const send = debounce((text) => console.log("sent", text), 500, { leading: true, trailing: false });
send("hi"); // "sent hi" at once
send("hi"); // ignored: same burst
// 500 ms of quiet, then:
send("again"); // "sent again" at onceconst save = debounce((draft) => console.log("saved", draft), 1000, { maxWait: 5000 });
// typing without a pause from 0 to 12 s, one call every 200 ms:
// "saved" at 5 s, at 10 s, and 1 s after the last keyconst log = debounce((value) => value * 2, 100);
log(1); // undefined: fn has not run
log.pending(); // true
log.flush(); // 2: fn ran now with 1
log(5); // 2: the result of the last run
log.cancel(); // the call with 5 never runsEnvironment
- Plain JavaScript in a browser page; the tests call the global
debouncefromdebounce.js. - The tests run on a virtual clock that replaces
setTimeout,clearTimeoutandDate.now; use those. Timers due at a moment run before a call made at that same moment. - The expected timelines in the tests are the ones lodash produces for the same calls.
- A plain debounce without options is problem 15.1.
Hints
- Which times do you need to remember to answer "has the burst ended?" and "has maxWait passed?"
- When the timer fires but a call came in meanwhile, does the burst end, or does the timer need to wait a little longer? How much longer?
- How can you tell, at the end of a burst, whether any call came after
fnlast ran?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it