Debouncing delays a function until the caller stops firing it for a set interval — great for "search as you stop typing." But plain debounce has a failure mode: if the calls never pause, the function never runs. maxWait fixes that. It guarantees the function fires at least once every maxWait milliseconds during a continuous burst, so a busy user still gets periodic updates.
Implement debounce(fn, wait, options). It behaves like normal debounce — each call restarts the wait timer — but if options.maxWait is set, fn must also fire whenever maxWait ms have elapsed since the burst began, whichever comes first. Always invoke with the most recent arguments.
function debounce(fn, wait, options) {
// options: { maxWait }
// returns a debounced function
}
// Fires 300ms after the user stops typing:
const search = debounce(runSearch, 300);
// Fires when idle 300ms OR at least once every 1000ms of steady typing:
const search = debounce(runSearch, 300, { maxWait: 1000 });
wait timer; fn runs only after wait ms of silence.maxWait ceiling — starts on the first call of a burst and is not reset by later calls; when it elapses, fn fires even if calls are still coming.maxWait ceiling race; the earlier one wins, then a new burst begins.fn is always invoked with the arguments (and this) of the most recent call.maxWait — behaves as a plain debounce (a never-ending burst never fires).Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.