JavaScript Debouncing vs Throttling
What Are Debouncing and Throttling?
Both Debouncing and Throttling are performance optimization techniques in JavaScript. They are commonly used to limit how often a function is executed, especially in response to events like:
- scroll
- resize
- input
- keypress
Why Are They Needed?
Without optimization, functions tied to fast-firing events can:
- Overwhelm the browser
- Cause lag
- Lower app performance
Debouncing
Definition:
Debouncing delays execution of a function until a certain time has passed since the last time it was invoked.
Ideal for:
- Search input boxes
- Form validation
- Window resize
Example: Debounce Search Input
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
function searchInputHandler(e) {
console.log("Searching for:", e.target.value);
}
const debouncedSearch = debounce(searchInputHandler, 500);
document.getElementById("search").addEventListener("input",
debouncedSearch);
If the user keeps typing, searchInputHandler won't run until 500ms of inactivity.
Throttling
Definition:
Throttling ensures a function is only executed once every specified amount of time, no matter how many times it's triggered.
Ideal for:
- Scroll events
- Button spam prevention
- Mouse move tracking
Example: Throttle Scroll Event
function throttle(func, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
func.apply(this, args);
}
};
}
function scrollHandler() {
console.log("Scroll event fired at", new
Date().toLocaleTimeString());
}
const throttledScroll = throttle(scrollHandler, 1000);
window.addEventListener("scroll", throttledScroll);
This runs scrollHandler once per second even if the scroll event fires 100+ times per second.
Difference Between Debounce and Throttle
Feature | Debounce | Throttle |
---|---|---|
Purpose | Waits for pause in activity | Limits calls per time interval |
Timing | After user stops triggering | At regular intervals |
Use Cases | Input fields, resize events | Scroll, mousemove, drag/drop |