Debouncing is a technique used to limit how often a function is executed.
- It ensures that a function is called only after a certain delay has passed since the last time it was invoked.
- Common use cases:
- Search input: wait until user stops typing to fetch results.
- Window resize: avoid firing events on every pixel change.
⚡ Simple Debounce Function
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId); // cancel previous timer
timeoutId = setTimeout(() => {
fn.apply(this, args); // call function after delay
}, delay);
};
}
🧩 Example: Debounced Search Input
const searchInput = document.getElementById("search");
function fetchResults(query) {
console.log("Fetching results for:", query);
}
// Wrap the function with debounce (500ms delay)
const debounceFetch = debounce(fetchResults, 500);
searchInput.addEventListener("input", (e) => {
debounceFetch(e.target.value);
});
✅ Behavior:
- While the user is typing rapidly,
fetchResultswon’t be called. - Only after the user stops typing for 500ms, the function executes.
💡 Key Points:
- Reduces unnecessary function calls.
- Improves performance for frequent events like
scrollorinput. - Uses
setTimeoutandclearTimeoutinternally.
In short:
Debouncing = “wait until the user stops triggering the event” before running the function.