Sub topic 9
Adding cancel and flush
A debounced function holds a call in reserve. Most of the time you want that: the call runs after the burst ends. Sometimes the program has to decide what happens to the reserved call before its timer fires. A component may unmount while a search request is still waiting. A user may close the tab while an autosave is waiting. A form may submit before the last keystroke's validation has run.
This chapter adds two methods to the trailing-edge debounce from earlier chapters:
cancel()drops the pending call. The wrapped function does not run.flush()runs the pending call right away and returns its result. If nothing is pending, it does nothing.
The chapter assumes you are comfortable with the trailing-edge debounce, with closures over timerId, and with preserving this and arguments through fn.apply.
Why the basic debounce can't do this
The first version kept only timerId in its closure. The arguments lived inside the arrow function passed to setTimeout:
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}Adding a cancel to this is easy because you only need to clear the timer. Flush is harder. To run the pending call now, you need the this and arguments it would have used, and those are captured inside a callback you can't reach. The fix is to move them out of the timer callback and into the shared closure, where every method can read them.
The full implementation
function debounce(fn, wait) {
let timerId;
let lastThis;
let lastArgs;
function invoke() {
const ctx = lastThis;
const args = lastArgs;
timerId = undefined;
lastThis = undefined;
lastArgs = undefined;
return fn.apply(ctx, args);
}
function debounced(...args) {
lastThis = this;
lastArgs = args;
clearTimeout(timerId);
timerId = setTimeout(invoke, wait);
}
debounced.cancel = function () {
clearTimeout(timerId);
timerId = undefined;
lastThis = undefined;
lastArgs = undefined;
};
debounced.flush = function () {
if (timerId !== undefined) {
clearTimeout(timerId);
return invoke();
}
};
return debounced;
}The structure has three parts.
- Shared state.
timerId,lastThis, andlastArgsdescribe the pending call.timerId !== undefinedis the single test for "a call is pending". - One invocation path. Both the timer and
flushgo throughinvoke. Whichever way the call runs, the state gets reset the same way. - Methods as properties. Functions are objects in JavaScript, so
debounced.cancelanddebounced.flushattach directly to the returned function. Callers keep usingdebounced(...)as before.
Why invoke resets state before calling fn
invoke copies the context and arguments into locals, clears the shared state, and only then calls fn. The order matters when fn calls the debounced function again, which is called re-entrancy. If the reset came after fn.apply, a nested call would schedule a new timer and store new arguments, and then the reset would wipe them. timerId would become undefined while a real timer was still scheduled, so a later flush would wrongly report nothing pending. Resetting first means a nested call starts from a clean state.
Why cancel clears lastArgs
Clearing timerId alone would stop the call. Clearing lastThis and lastArgs as well releases references. If the last argument was a DOM event, or this was a component instance, the debounced function would otherwise keep those objects reachable for as long as it exists. That is a small leak, but it is real in long-lived pages.
The lifecycle as a state machine
A debounced function with these controls is always in one of two states.
Calling either method while idle is safe. clearTimeout(undefined) does nothing, and flush checks timerId before invoking. This means cleanup code can call cancel() without first checking whether anything is pending.
Seeing it run
This script runs in Node or a browser console and shows all three outcomes:
// Uses the debounce with cancel and flush defined above
const log = debounce((label) => {
console.log('ran with', label);
return label.toUpperCase();
}, 200);
// 1. Normal trailing call
log('a');
log('b'); // after 200 ms: "ran with b"
// 2. Cancel
setTimeout(() => {
log('c');
log.cancel(); // "c" never runs
}, 400);
// 3. Flush
setTimeout(() => {
log('d');
const result = log.flush(); // "ran with d" immediately
console.log('flush returned', result); // "D"
console.log('second flush', log.flush()); // undefined, nothing pending
}, 800);Expected output:
ran with b
ran with d
flush returned D
second flush undefinedWhere each method belongs
| Situation | Method | Reason |
|---|---|---|
| Component unmounts with a search pending | `cancel` | The result would update UI that no longer exists |
| User navigates away from a filtered list | `cancel` | The request is for a view the user left |
| Form submit while validation is debounced | `flush` | Submit must see the latest validation result |
| Tab hidden or closing with an unsaved draft | `flush` | Losing the last edits is worse than saving early |
| Test needs the pending call to run now | `flush` | No need to wait or fake timers for this check |
| User presses Escape to clear a search box | `cancel` | The pending query is for text that is gone |
A useful rule: if the pending call's side effect is still wanted, flush it. If the context that made it meaningful has gone away, cancel it.
Flushing on page exit
Saving a draft when the page goes away is the most common use of flush, and it has a trap. Browsers do not wait for asynchronous work during unload. A fetch started in beforeunload may be dropped. Use a synchronous store or navigator.sendBeacon, and listen for visibilitychange, which fires more reliably than beforeunload, especially on mobile:
const editor = document.querySelector('#editor');
const saveDraft = debounce((text) => {
navigator.sendBeacon('/api/draft', text);
}, 1000);
editor.addEventListener('input', (e) => saveDraft(e.target.value));
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
saveDraft.flush();
}
});Common errors
Cancelling a different debounced function
// Bug: a new debounced function every time
element.addEventListener('input', (e) => debounce(search, 300)(e.target.value));
// Later...
debounce(search, 300).cancel(); // cancels a brand-new, idle instanceEach call to debounce creates its own closure with its own timer. cancel and flush only affect the instance you call them on. Create the debounced function once and keep a reference to it. The React chapter returns to this problem, because re-renders recreate functions by default.
Expecting cancel to abort work already started
cancel stops a call that has not run yet. If the timer already fired and fn started a network request, cancel has nothing to clear. To abort in-flight work, pair the debounce with an AbortController:
let controller;
const search = debounce(async (query) => {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
console.log(await res.json());
} catch (err) {
if (err.name !== 'AbortError') throw err;
}
}, 300);
function teardown() {
search.cancel(); // drop a call that hasn't started
controller?.abort(); // abort a request that has
}Expecting a return value from the debounced call
debounced(...) always returns undefined, because the real call happens later. Only flush can return fn's result, and only when a call was pending. If callers need results from every call, return a Promise from the wrapper, or debounce the side effect and leave the value-producing code undebounced.
Edge cases worth knowing
- Flush, then the old timer.
flushclears the timer before invoking, so the call can't run twice. ForgettingclearTimeoutinflushis a classic double-call bug. - Cancel inside fn. Because
invokeresets state first, callingdebounced.cancel()from insidefncancels only calls thatfnitself scheduled. - Exceptions. If
fnthrows, state has already been reset, so the debounced function stays usable. The error propagates to whoever calledflush, or becomes an uncaught error if the timer triggered the call. - Zero wait.
debounce(fn, 0)still defers to a later task.flushis the only way to run it synchronously.
Exercise
Add a pending() method to the debounce implementation that returns true when a call is waiting to run and false otherwise. Which single piece of state should it read, and why is that enough?
Show answer
Add debounced.pending = function () { return timerId !== undefined; };. timerId is enough because every path that schedules a call sets it (debounced), and every path that ends a pending call resets it to undefined (invoke, which both the timer and flush use, and cancel). Because invoke resets state before calling fn, pending() also returns the correct answer when fn re-schedules itself.
Exercise
A teammate writes flush as debounced.flush = function () { if (timerId !== undefined) return invoke(); };, leaving out clearTimeout. What goes wrong, and when?
Show answer
invoke sets timerId to undefined but the scheduled timer still exists. When it fires, it calls invoke again, so fn runs a second time with lastThis and lastArgs both undefined (they were already cleared). The bug appears whenever flush is called while a call is pending, which is exactly the case flush exists for.
Exercise
A chat app debounces a "user is typing" notification with a 500 ms wait. Decide whether cancel or flush belongs in each case: (1) the user presses Enter to send the message, (2) the user clears the input with a close button, (3) the chat window component unmounts.
Show answer
(1) cancel, because the message being sent replaces the typing notice, and sending a late "typing" event would be wrong. (2) cancel, because the user is no longer typing anything. (3) cancel, because the component and its connection are going away. Flush fits when the pending side effect still matters, such as saving data. A transient presence signal stops mattering once the situation changes.