Debouncing is a technique used to delay execution of a function until after a specified period of inactivity.
It ensures that the function is called only once after the event stops firing for
X ms
.
🔁 Difference from Throttling:
Debouncing | Throttling | |
---|---|---|
Executes | Once after a pause | Every X ms, even during activity |
Ideal For | Search box, validation | Scroll, resize, rapid clicks |
💡 Real-World Examples of Debouncing
Use Case | Why Use Debounce? |
---|---|
Search Input | Avoid firing API on each keypress |
Form Validation | Wait until user stops typing |
Window Resize | Perform layout update after resize stops |
Live Suggestions | API call only when user pauses typing |
✅ Debounce Utility Function
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
The clearTimeout() prevents the previous scheduled setTimeout() from firing. So, as long as the time between two function calls is less than delay, the actual func() will never be called.
Only when there's a pause longer than or equal to delay, the final scheduled setTimeout() will run and invoke func().
🧪 Example 1: Debounced Search Box
type="text" id="search" placeholder="Type something..." />
function search(query) {
console.log("Searching for:", query);
}
const debouncedSearch = debounce((e) => search(e.target.value), 500);
document.getElementById("search").addEventListener("input", debouncedSearch);
⏱️ Behavior:
- User types:
"J" → "Ja" → "Jav" → "Java"
-
search()
is called only once after user pauses typing for 500ms.
🔐 Example 2: Live Email Validator
function validateEmail(email) {
console.log("Validating email:", email);
// AJAX/API call can go here
}
const input = document.getElementById("email");
input.addEventListener("input", debounce(e => validateEmail(e.target.value), 700));
✅ Debouncing Summary
Feature | Description |
---|---|
Delays | Executes after pause in event stream |
Saves calls | Prevents unnecessary repeated execution |
Use Cases | Inputs, search fields, validation, resize |
If you want, I can create a full mini project with both throttling & debouncing demo, or even combine with backend rate-limiting logic!