A search box fires an event on every keystroke. A scroll handler fires dozens of times per second. Handling each one with an API call or a heavy calculation is wasteful — and debounce and throttle are the two techniques that fix it. They solve the same problem differently, and knowing which to use matters.
Debounce waits until the user stops. Each new event resets the timer, so the function runs only after a quiet period:
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
const search = debounce((query) => {
console.log("Searching for:", query);
}, 300);
document.getElementById("search").addEventListener("input", (e) => {
search(e.target.value);
});
Type fast and nothing happens; pause for 300ms and one search runs. Debounce is for search boxes, auto-save, and anything where only the final value matters.
Throttle runs at most once per interval, no matter how many events fire:
function throttle(fn, limit) {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn(...args);
}
};
}
const onScroll = throttle(() => {
console.log("Scroll position:", window.scrollY);
}, 200);
window.addEventListener("scroll", onScroll);
Scroll a hundred times in a second and the handler runs about five times — enough to update a progress bar, not enough to freeze the page. Throttle is for scroll, resize, and mousemove — anything where you need regular updates, not just the last one.
The difference in one line: debounce says "run when the user stops", throttle says "run at most this often". A search box needs debounce; a scroll progress bar needs throttle; mixing them up gives you either a laggy search or a progress bar that only updates when you stop scrolling.
A leading-edge throttle runs immediately on the first event, then waits — useful for a button that should respond instantly but not twice:
function throttleLeading(fn, limit) {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn(...args);
}
};
}
Two mistakes beginners make: first, creating a new debounced function on every render, which resets the timer each time and breaks the debounce entirely — create it once, outside the handler. Second, debouncing the wrong thing — debounce the expensive work (the API call), not the cheap work (updating the input's own value).
Ways to extend it: combine both — a throttled scroll handler that debounces the final save, use requestAnimationFrame as a throttle for visual updates, or reach for Lodash's battle-tested versions once you understand the pattern. These two tiny functions save more API calls and battery than almost any optimisation you will write.
Top comments (0)