Both debouncing and throttling are techniques to control how often a function is executed, especially for events that fire frequently like scroll, resize, or input.
🔹 1. Debouncing
- Definition: Ensures a function is executed only after a certain delay has passed since the last time it was invoked.
- Use Case: Search input, autocomplete, window resizing.
Example:
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage:
const handleInput = debounce(() => console.log("Searching..."), 500);
document.getElementById("search").addEventListener("input", handleInput);
✅ Effect: The function runs only once after the user stops typing for 500ms.
🔹 2. Throttling
- Definition: Ensures a function is executed at most once every specified time interval, no matter how many times the event is triggered.
- Use Case: Scroll events, infinite scroll, mouse move.
Example:
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function (...args) {
if (!lastRan) {
func.apply(this, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(this, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
// Usage:
const handleScroll = throttle(() => console.log("Scrolling..."), 1000);
window.addEventListener("scroll", handleScroll);
✅ Effect: The function runs once every 1 second regardless of how fast the user scrolls.
🧭 Key Differences
| Feature | Debounce | Throttle |
|---|---|---|
| Execution | After user stops triggering | At regular intervals |
| Use Case | Search input, resize events | Scroll, mouse move, API polling |
| Frequency | Once after idle | Once per interval |