Sub topic 10
Bounding the Wait with maxWait
This chapter assumes you have built the trailing-edge debounce from earlier chapters. It also assumes you know how setTimeout and clearTimeout work and how fn.apply(this, args) passes on context and arguments.
The Problem: A Debounce That Never Fires
A trailing debounce runs only after the calls stop. That is usually what you want. Sometimes, though, the calls don't stop. Picture a user typing a long document without pausing for 300 ms, or a sensor sending a reading every 50 ms. Each call resets the timer, so the function never runs. An autosave built this way saves nothing until the user stops typing, and if the tab crashes first, the work is lost.
maxWait fixes this. It is an upper limit on how long a call can be delayed. The function still waits for a quiet period of wait ms, but it never waits longer than maxWait ms from the first call in a burst.
How It Works
The debounced function keeps two timers:
- The wait timer is reset on every call, as in a normal debounce.
- The max timer starts on the first call of a burst and is never reset. When it fires, the function runs even though calls are still coming in.
Whichever timer fires first calls the function. That call clears both timers, so the next call starts a new burst.
Implementation
function debounceMaxWait(fn, wait, maxWait) {
let timerId;
let maxTimerId;
let lastThis;
let lastArgs;
function invoke() {
clearTimeout(timerId);
clearTimeout(maxTimerId);
timerId = undefined;
maxTimerId = undefined;
const ctx = lastThis;
const args = lastArgs;
lastThis = undefined;
lastArgs = undefined;
fn.apply(ctx, args);
}
return function (...args) {
lastThis = this;
lastArgs = args;
clearTimeout(timerId);
timerId = setTimeout(invoke, wait);
if (maxTimerId === undefined) {
maxTimerId = setTimeout(invoke, Math.max(maxWait, wait));
}
};
}
// Demo: run with Node. Calls arrive every 100 ms for 2 seconds.
const start = Date.now();
const save = debounceMaxWait((n) => {
console.log(`saved call #${n} at ${Date.now() - start} ms`);
}, 300, 1000);
let n = 0;
const intervalId = setInterval(() => save(++n), 100);
setTimeout(() => clearInterval(intervalId), 2000);Without maxWait, this demo would print one line, about 300 ms after the calls stop. With maxWait set to 1000, it prints about once per second while the calls continue. Each line shows the most recent call number.
Common Errors
- Resetting the max timer on every call. If you clear
maxTimerIdinside the wrapper, it behaves exactly like the wait timer, and you are back to a debounce that never fires. - Forgetting to clear the other timer in
invoke. If the max timer fires and the wait timer is left running, the function runs a second time with stale orundefinedarguments. - Setting
maxWaitsmaller thanwait. That setting means nothing useful, which is why the code usesMath.max(maxWait, wait). Lodash applies the same rule.
Where maxWait Sits Between Debounce and Throttle
| Technique | Runs during a continuous burst? | Runs after the burst ends? |
|---|---|---|
| Trailing debounce | Never | Once, after `wait` |
| Debounce with `maxWait` | At least every `maxWait` ms | Once, after `wait` |
| Throttle | Every `wait` ms | Depends on trailing option |
As maxWait gets closer to wait, a debounce starts to behave like a throttle. Lodash relies on this: its throttle is implemented as debounce with maxWait equal to wait and leading: true.
Exercise
A debounced autosave uses wait = 1000 and maxWait = 5000. The user types continuously, one key every 200 ms, for 12 seconds, then stops. Roughly when does the save run?
Show answer
The first keystroke at 0 s starts the max timer, so a save runs at about 5 s. The next keystroke starts a new burst, which gives another save at about 10 s. Typing stops at 12 s, and the wait timer fires about 1 s later, so the last save runs at about 13 s. That is three saves in total.
Exercise
In debounceMaxWait, what goes wrong if invoke clears only maxTimerId and leaves timerId running?
Show answer
After the max timer runs the function, the pending wait timer still fires later and calls invoke again. lastArgs has already been reset to undefined, so fn runs a second time with no arguments.