Sub topic 9
Adding cancel and flush
This chapter assumes you have already built the trailing-edge debounce from earlier chapters, and that you know how it keeps this and the arguments with fn.apply(this, args). It also assumes you are comfortable with closures and clearTimeout.
A plain debounced function only lets you schedule a call. Real applications also need to control a call that is already scheduled:
- cancel drops the pending call. Use it when the thing the call would touch is going away. Examples are a component that unmounts, a modal that closes, or a request that no longer matters.
- flush runs the pending call right now instead of waiting. Use it when you need the result before the timer would fire. Examples are saving a draft before the page closes, or submitting a form while a validation call is still waiting.
The working model
A debounced function is always in one of two states: idle, with no timer, or pending, with a timer and saved this and arguments. Calling the function moves it to pending, or restarts the timer if it is already pending. Pending ends in one of three ways: the timer fires, cancel drops the call, or flush runs it early.
The implementation
To support these controls, the saved context and arguments have to live in the closure, not inside the setTimeout callback. That way flush can reach them. A shared invoke helper does the actual call, so the timer and flush follow the same path.
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;
}Some details in this code matter:
timerId === undefinedmeans idle. Bothinvokeandcancelreset it, soflushcan tell whether a call is waiting.invokeclears its state before it callsfn. Iffncalls the debounced function again, that new call starts a fresh timer and is not erased afterward.- Clearing
lastThisandlastArgslets the garbage collector reclaim objects you no longer need, such as event objects or DOM nodes. flushreturns whateverfnreturns. When nothing is pending, it returnsundefinedand does not callfn.
Using both controls
const saveDraft = debounce((text) => {
localStorage.setItem('draft', text);
console.log('Saved:', text);
}, 1000);
const editor = document.querySelector('#editor');
const onInput = (event) => saveDraft(event.target.value);
editor.addEventListener('input', onInput);
// Save immediately if the user leaves before the timer fires.
window.addEventListener('beforeunload', () => saveDraft.flush());
// Teardown: stop listening and discard any pending save.
function destroyEditor() {
editor.removeEventListener('input', onInput);
saveDraft.cancel();
}Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Arguments saved only inside the timer callback | `flush` has nothing to run | Store `lastThis` and `lastArgs` in the closure |
| `flush` calls `fn` without checking for a timer | `fn` runs with `undefined` arguments | Guard with `timerId !== undefined` |
| State reset after `fn` runs | A re-entrant call made inside `fn` is lost | Reset state before calling `fn` |
| Removing the listener but not calling `cancel` on teardown | A late call hits removed elements | Call `cancel` in cleanup code |
Exercise
You call debounced('a'), then debounced.cancel(), then debounced.flush(). How many times does fn run, and what does flush return?
Show answer
Zero times. cancel clears the timer and sets timerId to undefined, so flush finds nothing pending, skips invoke, and returns undefined.
Exercise
A debounced save function returns a Promise. How can a "Submit" handler make sure the latest pending save has finished before it continues?
Show answer
Call await debounced.flush(). If a save is pending, flush runs it right away and returns its Promise, which you can await. If nothing is pending, flush returns undefined, and awaiting undefined resolves at once.