Debouncing and Throttling Event Handlers
What you'll learn: How to limit how often expensive functions run in response to rapid-fire events like scrolling, resizing, or typing.
The Problem
Events like scroll, resize, mousemove, and input can fire hundreds of times per second. If your handler does something expensive—like DOM manipulation, API calls, or calculations—you'll overload the main thread and create a janky user experience.
Two Patterns to Control Frequency
Debouncing waits for a "quiet period" before executing. Imagine a search box: you don't want to query the server on every keystroke—you wait until the user stops typing for, say, 300ms.
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
const searchInput = document.querySelector('#search');
const expensiveSearch = debounce((e) => {
console.log('Searching for:', e.target.value);
// API call here
}, 300);
searchInput.addEventListener('input', expensiveSearch);
Throttling limits execution to once per time period. Think of a scroll progress indicator: you want updates regularly (every 100ms), but not on every single scroll event.
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
const handleScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 100);
window.addEventListener('scroll', handleScroll);
When to Use Which
- Debounce: Search inputs, form validation, window resize handlers (wait for final size)
- Throttle: Scroll progress, infinite scroll triggers, position tracking
Key Takeaway: Debouncing waits for silence before executing; throttling ensures regular execution intervals. Both prevent main thread overload from high-frequency events, dramatically improving responsiveness.