- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Debounce
JavaScript Performance
JavaScript Debounce
Debouncing delays a function until the calls have stopped for a while.
Typing in a search box can fire an event on every keystroke.
Debouncing waits until typing pauses before doing the expensive work.
Example
Example
javascript
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(function () {
fn(...args);
}, delay);
};
}
let calls = 0;
const debounced = debounce(function () { calls++; }, 10);
debounced();
debounced();
debounced();
console.log(calls);