Sub topic 10
Bounding the Wait with maxWait
A trailing-edge debounce runs only after the calls stop. That works when input arrives in short bursts. It fails when the input does not stop. A user who types without pausing, a window that keeps resizing during a drag, or a sensor that streams readings will keep pushing the timer forward, so the debounced function may never run. The maxWait option fixes this by putting an upper limit on how long a pending call can be delayed.
This chapter assumes you have already built the trailing debounce with its cancel and flush methods from earlier chapters, and that you know how setTimeout delays behave in the event loop.
The Starvation Problem
Suppose you autosave a document with debounce(save, 1000). A fast typist who never pauses for a full second produces a burst of keystrokes with no gap long enough to fire the timer. Each keystroke calls clearTimeout and schedules a new timer. If the user types steadily for ten minutes, nothing is saved for ten minutes. If the tab crashes, all of that work is lost.
This is called starvation: the debounced function is held back for as long as the calls keep coming. Plain debounce gives no guarantee about the longest possible delay. It only guarantees a quiet period before the call.
What maxWait Guarantees
maxWait adds a second rule on top of the debounce rule:
- Run the function
waitmilliseconds after the last call (the normal debounce rule). - Also run it if
maxWaitmilliseconds have passed since the pending burst started, even if calls are still arriving.
Whichever rule triggers first wins. After the function runs, the burst counts as finished. The next call starts a new one with fresh timers.
The result is a function that still waits for quiet periods when they happen, but never stays silent for longer than maxWait during continuous input.
Implementing maxWait with Two Timers
The simplest correct approach uses two timers. The wait timer is reset on every call, as in a plain debounce. The max timer is set only by the first call of a burst and is never reset. When either timer fires, it runs the same invoke function, which clears both timers and ends the burst.
function debounce(fn, wait, maxWait) {
const hasMax = maxWait !== undefined;
const maxDelay = hasMax ? Math.max(maxWait, wait) : undefined;
let timerId;
let maxTimerId;
let lastThis;
let lastArgs;
function clearTimers() {
clearTimeout(timerId);
clearTimeout(maxTimerId);
timerId = undefined;
maxTimerId = undefined;
}
function invoke() {
const ctx = lastThis;
const args = lastArgs;
clearTimers();
lastThis = undefined;
lastArgs = undefined;
return fn.apply(ctx, args);
}
function debounced(...args) {
lastThis = this;
lastArgs = args;
clearTimeout(timerId);
timerId = setTimeout(invoke, wait);
if (hasMax && maxTimerId === undefined) {
maxTimerId = setTimeout(invoke, maxDelay);
}
}
debounced.cancel = function () {
clearTimers();
lastThis = undefined;
lastArgs = undefined;
};
debounced.flush = function () {
if (timerId !== undefined || maxTimerId !== undefined) {
return invoke();
}
};
return debounced;
}Some details in this code are easy to miss:
maxTimerId === undefinedis what makes the max timer belong to the burst and not to each call. It is set once and left alone untilinvokeclears it.invokeclears both timers before callingfn. If it did not, the wait timer would fire again after a maxWait call and run the handler a second time with stale orundefinedarguments.cancelandflushnow have two timers to handle. Acancelthat clears onlytimerIdwould leave the max timer running, and the "cancelled" call would still happen.- The max timer runs the function with the most recent
thisand arguments, not those from the call that started the burst. That is usually what you want: an autosave should save the current text, not the text from a second ago.
Watching It Run
You can run this in Node or a browser console. It simulates a call every 50 ms for 2.5 seconds.
const start = Date.now();
const report = debounce((n) => {
console.log(`${Date.now() - start} ms: ran with call #${n}`);
}, 300, 1000);
let n = 0;
const intervalId = setInterval(() => report(n++), 50);
setTimeout(() => clearInterval(intervalId), 2500);
// Approximate output (exact numbers vary by a few ms):
// 1050 ms: ran with call #19
// 2100 ms: ran with call #40
// 2750 ms: ran with call #48Without the third argument, the same script logs a single line at about 2750 ms. With maxWait, the handler runs roughly once per second while input continues, then one last time after the input stops.
How maxWait Relates to Throttle
Look at what happens when maxWait equals wait. The wait timer resets on every call, so during continuous input it never fires. The max timer fires every wait milliseconds. When input stops, the last burst is flushed by whichever timer comes first. That is a throttle with a trailing call.
Lodash takes advantage of this directly. Its throttle(fn, wait) is built as debounce(fn, wait, { leading: true, trailing: true, maxWait: wait }). Debounce and throttle are two settings of the same mechanism:
| Configuration | Behavior during continuous input | Behavior after input stops |
|---|---|---|
| `debounce(fn, 300)` | Never runs | Runs once, 300 ms later |
| `debounce(fn, 300, 1000)` | Runs about every 1000 ms | Runs once, 300 ms later or sooner |
| `debounce(fn, 300, 300)` | Runs about every 300 ms | Runs once with the final arguments |
| `throttle(fn, 300)` with trailing | Runs about every 300 ms | Runs once with the final arguments |
A useful way to think about the choice: maxWait sets how stale your output is allowed to get, and wait sets how long a pause counts as "the user is done."
Choosing a maxWait Value
Pick maxWait from the cost of being late, not from the event rate.
| Use case | Typical `wait` | Typical `maxWait` | Reason for the bound |
|---|---|---|---|
| Autosaving a draft | 1000 ms | 5000 ms | Limits how much work is lost if the page crashes |
| Search-as-you-type | 300 ms | 1000 to 1500 ms | Shows some results during long queries |
| Layout recalculation on resize | 150 ms | 500 ms | Keeps the layout from looking broken mid-drag |
| Batching analytics events | 2000 ms | 10000 ms | Caps the age of buffered events |
If maxWait is close to wait, you have built a throttle, and you should probably use one so the intent is clear to readers. If maxWait is many times larger than wait, it acts as a safety net that rarely triggers in normal use.
Edge Cases and Gotchas
maxWait Smaller Than wait
If maxWait is less than wait, the max timer always fires first, and the debounce rule never matters. The implementation above clamps the value with Math.max(maxWait, wait), which matches Lodash. Without the clamp you would get a throttle at the maxWait rate while the code says something else.
Where the Next Window Starts
In the two-timer version, the next window starts at the first call after an invocation. Lodash measures from the time of the last invocation. Under steady input the difference is at most one event interval, which is 50 ms in the demo above. It can matter if input is sparse: with the two-timer version, a call that arrives long after the last run starts a fresh full maxWait window, so it is governed by wait like any normal debounce.
Timers Are Not Deadlines
setTimeout sets a minimum delay. A long task on the main thread pushes both timers back. Browsers also slow down timers in background tabs, often to once per second or less. maxWait bounds the delay in normal conditions. It does not make a real-time guarantee. For work that must not be lost when the page closes, also call flush in a pagehide or beforeunload handler.
Leading Calls
If you combine maxWait with a leading-edge option, the first call runs immediately and starts the burst. Decide whether the max timer should then measure from that leading call. Lodash does, which is why its throttle produces calls at 0, wait, 2 × wait, and so on. Writing your own leading-plus-maxWait logic means handling all three triggers (leading, trailing, max) without running the function twice for the same call. At that point a tested library is usually the better choice.
Exercise
A debounced autosave uses debounce(save, 1000, 5000). The user types steadily, one key every 200 ms, for 12 seconds, then stops. Roughly when does save run, and how many times?
Show answer
The pause between keys (200 ms) is always shorter than wait (1000 ms), so the wait timer never fires during typing. The max timer fires about every 5 seconds: around 5 s and around 10 s. Typing stops at 12 s, and the final burst started around 10.2 s, so its max timer would fire near 15.2 s. The wait timer fires first, about 1 s after the last key, near 13 s. That makes three saves, at about 5 s, 10 s, and 13 s.
Exercise
A teammate's maxWait implementation clears only the wait timer inside invoke and leaves the max timer alone. Describe the bug a user would see.
Show answer
When the wait timer runs the function, the max timer keeps running. It fires later and calls invoke again. By then lastArgs has been cleared, so fn runs with undefined arguments, or with stale ones if the code does not reset them. The user sees an extra, unexpected call after the burst ends, such as an empty search request or a duplicate save.
Exercise
Why does debounce(fn, 200, 200) behave like a throttle with a trailing call, and why would you still write throttle(fn, 200) in real code?
Show answer
When calls arrive faster than 200 ms apart, the wait timer is reset before it can fire, so only the max timer runs fn, once every 200 ms, with the latest arguments. When calls stop, the pending call is flushed, which is the trailing call. The behavior matches, but throttle(fn, 200) states the intent directly, and a reader can understand it without working through the timer interaction.