Debounce
JS · Common Patternssyntax
function debounce(fn, delay) { ... }example
function debounce(fn, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), delay);
};
}
// Usage: only fire after user stops typing for 300ms
const searchInput = document.querySelector("#search");
searchInput.addEventListener("input",
debounce((e) => {
console.log("Searching:", e.target.value);
}, 300)
);Note Debouncing delays execution until activity stops for a given period. Ideal for search inputs, window resize handlers, and form validation.