Debouncing Without Losing the Last Event
A small pattern for coalescing noisy input while guaranteeing the final value is always handled.
- Realtime
- Debouncing
- TypeScript
- Events
Search boxes, resize observers and live filters produce events faster than a UI can usefully react to them. Debouncing is the obvious fix, but the naive version drops the trailing edge: the last keystroke never reaches the server, and the user watches a stale result set settle.
The trailing edge matters
A timer-based debounce that only fires when there is a pause works while the user keeps typing. The moment a request is in flight or the component unmounts, that final call can be lost. Treat the last event as a promise you owe the user, not an optional extra.
export function debounce<T extends (...args: never[]) => void>(
fn: T,
wait: number,
): ((...args: Parameters<T>) => void) & { flush: () => void } {
let timer: ReturnType<typeof setTimeout> | undefined;
let pending: Parameters<T> | undefined;
const run = () => {
if (pending) {
const args = pending;
pending = undefined;
fn(...args);
}
};
const debounced = (...args: Parameters<T>) => {
pending = args;
clearTimeout(timer);
timer = setTimeout(run, wait);
};
debounced.flush = () => {
clearTimeout(timer);
run();
};
return debounced;
}
Flush on the boundaries that matter
Call flush() when the field loses focus, when the form submits, and when the component unmounts. Those are the three moments where a trailing value has to be observable. Everything else can wait for the quiet interval.
Keep the request, not just the callback
For network work, debounce the call and cancel the previous in-flight request with an AbortController. A debounce prevents duplicates; cancellation prevents a slower older response from overwriting a newer one. They solve different races, so both are needed.
Make the delay visible
A 250ms pause reads as instant. A 900ms pause feels broken unless the interface shows that something is pending. Pair the debounce with a small pending indicator and the delay becomes a deliberate trade-off rather than a mysterious lag.