Skip to curriculum
Jump to the editor

15.2. Debounce with leading edge, maxWait, cancel and flush

Hard
Topics

This question is in

15. Debounce and throttle
40–60 min

A 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

JAVASCRIPT
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 progress
  • options.leading (default false): run fn at the first call of a burst.
  • options.trailing (default true): run fn when the burst ends.
  • options.maxWait (default: none): never delay fn longer 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

  1. With no options it is a plain debounce: fn runs once, wait ms after the last call of a burst.
  2. Every call returns the result of fn's most recent run, or undefined if it has not run yet.
  3. leading: true: the first call of a burst runs fn at once, and that call returns the new result. Later calls in the same burst do not run it at once.
  4. The trailing run at the end of a burst happens only when trailing is true and a call came after fn last ran. So with leading and trailing both on, a single call runs fn once, and a burst of several calls runs it twice.
  5. leading: true, trailing: false runs fn once per burst. With both off, fn never runs.
  6. maxWait: during a long burst, once maxWait ms have passed since fn last ran (or since the burst began), fn runs with the latest call. A maxWait smaller than wait counts as wait. Without the option, there is no such limit.
  7. cancel() stops the timer, drops the waiting call and forgets the burst, so the next call starts a new one (and runs at once with leading). It is harmless when nothing waits.
  8. flush(), during a burst, ends it now: if trailing is on and a call is waiting, fn runs 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.
  9. pending() is true from the call that starts a burst until the burst ends, is flushed or is cancelled.
  10. Each debounced function has its own state. With wait 0 and no leading, fn still runs in a later timer, never during the call. A non-function fn throws a TypeError.

Examples

JAVASCRIPT
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 once
JAVASCRIPT
const 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 key
JAVASCRIPT
const 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 runs

Environment

  • Plain JavaScript in a browser page; the tests call the global debounce from debounce.js.
  • The tests run on a virtual clock that replaces setTimeout, clearTimeout and Date.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

  1. Which times do you need to remember to answer "has the burst ended?" and "has maxWait passed?"
  2. 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?
  3. How can you tell, at the end of a burst, whether any call came after fn last 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
Back to the question
Loading the editor…