Debounce a function
Delay a function call until the caller has stopped invoking it for a given time, with cancel support.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function debounce(fn, wait = 200) {
let timer;
function debounced(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
}
debounced.cancel = () => clearTimeout(timer);
return debounced;
}Example / expected output
// Rapid calls "a", "ab", "abc" within 200ms -> fn runs once with "abc"How it works
Debouncing collapses a burst of calls (typing, resizing, scrolling) into a single call that runs after the burst has been quiet for wait milliseconds. Use it for search-as-you-type or autosave.
- The returned function keeps the latest arguments and
this. - Call
.cancel()when a component unmounts so a pending call cannot fire late. - If you need the first call to run immediately, you want throttling instead.
Related snippets
- JavaScript Tested
Sleep / delay with a Promise
Pause an async function for a number of milliseconds, with optional cancellation through AbortSignal.
- JavaScript Tested
Run async tasks with a concurrency limit
Process a large list with at most N promises in flight at once, preserving result order.
- JavaScript Tested
Retry an async operation with exponential backoff
Retry a failing promise-returning function with growing, jittered delays and a retry predicate.
- Python Tested
Retry decorator with exponential backoff
Re-run a flaky function a limited number of times with growing delays, only for chosen exception types.

