debounce
Debounce is a timing technique that holds back a function while calls to it keep arriving, then runs it once after the calls have stopped for a set interval.
A debounced function restarts its waiting period on every call. Only the last call in a burst goes through, so many rapid events produce one run of the function. The term comes from electronics, where a debounce circuit ignores the rapid on and off signals of a mechanical switch.
Debouncing shows up wherever events fire faster than the work they trigger needs to run. Typical cases are search boxes that query a server as someone types, window resize handlers, and autosave. Running the work on every event would waste requests and slow the page.
The usual implementation is a higher-order function that wraps a callback. It keeps the pending timer in a closure and cancels and reschedules it with setTimeout() and clearTimeout(), timer functions that the runtime provides rather than the language itself. This version runs on the trailing edge, after the quiet period. Other versions also run on the leading edge, the first call of a burst.
Example
A search box often needs to query the server only once the user pauses typing. The debounce() helper below waits for 200 milliseconds without a keystroke before it runs the search, and the program simulates two bursts of typing:
debounce-search.mjs
function debounce(action, delay) {
let timerId;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => action(...args), delay);
};
}
const search = debounce((query) => {
console.log(`Searching for "${query}"`);
}, 200);
const keystrokes = [
[0, "j"],
[50, "ja"],
[100, "jav"],
[400, "java"],
[450, "javas"],
];
for (const [time, query] of keystrokes) {
setTimeout(() => {
console.log(`Typed: ${query}`);
search(query);
}, time);
}
Running the file shows one search per burst, each with the latest text:
$ node debounce-search.mjs
Typed: j
Typed: ja
Typed: jav
Searching for "jav"
Typed: java
Typed: javas
Searching for "javas"
Each keystroke clears the timer that the previous one scheduled, so "j" and "ja" never reach the server. The search runs only after a gap longer than 200 milliseconds, which happens once after "jav" and once after "javas".
The timeline below steps through the same five keystrokes and shows each call cancel the pending timer and schedule a new one:
Related Resources
Course
JavaScript Scope, Closures, and Functional Patterns for Pythonistas
Port a bouldering gym's front-desk script to JavaScript, and learn where names live and when they exist, how closures keep state, and how to work with rest parameters, callbacks, and timers.
For additional information on related topics, take a look at the following resources:
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 21, 2026