JavaScript Debounce with a Closure
A debounced function waits for quiet, then runs once. Fast repeated calls restart the wait, so only the last call runs.
Without debounce, every call runs
A plain search runs on every keystroke. Three calls print three searches.
function search(query) { console.log("Searching for " + query); }
search("j");
search("ja");
search("jav");Debounced, only the last call runs
The debounced search clears its timer on each call. Only the last call survives the wait, so only jav is searched.
function debounce(fn, wait) {
let timer;
return function (value) {
clearTimeout(timer);
timer = setTimeout(function () { fn(value); }, wait);
};
}
const search = debounce(function (query) {
console.log("Searching for " + query);
}, 50);
search("j");
search("ja");
search("jav");A quiet gap lets it run again
The first call runs after its wait ends. A later call starts a new wait and runs on its own.
function debounce(fn, wait) {
let timer;
return function (value) {
clearTimeout(timer);
timer = setTimeout(function () { fn(value); }, wait);
};
}
const search = debounce(function (query) {
console.log("Searching for " + query);
}, 50);
search("one");
setTimeout(function () { search("two"); }, 100);Example
function debounce(fn, wait) {
let timer;
return function (value) {
clearTimeout(timer);
timer = setTimeout(function () { fn(value); }, wait);
};
}
const search = debounce(function (query) {
console.log("Searching for " + query);
}, 50);
search("c");
search("ca");
setTimeout(function () { search("cat"); search("cats"); }, 100);Key points
- Debounce: a way to hold a function back until the calls stop for a set wait
- The closure holds the timer id between calls.
- Each new call clears the old timer and starts a fresh one.
- The function runs once, with the last call's arguments.
- A quiet gap longer than the wait lets the function run.
In this example, the first burst ends at ca, so the search runs once for ca. The second burst ends at cats, so the search runs once for cats. Four calls turn into two searches.
Note
Debounce suits search boxes and resize handlers, where only the last input matters.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a debounced function do when it is called three times in a row?