Debounce and Throttle Functions
You'll learn how closures maintain timing state to control how often functions execute in response to rapid events.
What Are Rate-Limiting Patterns?
Sometimes functions get called too often—think of a search bar that fires on every keystroke, or a scroll listener that triggers hundreds of times per second. Debounce and throttle are patterns that use closures to track timing state and limit execution frequency.
Debounce: Wait for the Quiet
Debounce ensures a function only runs after activity stops for a specified delay:
function debounce(func, delay) {
let timeoutId; // Closure captures this timer reference
return function(...args) {
clearTimeout(timeoutId); // Cancel previous timer
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
}
const search = debounce((query) => {
console.log('Searching for:', query);
}, 500);
// User types "hello"
search('h'); // Timer starts
search('he'); // Previous timer cancelled, new timer starts
search('hel'); // Cancelled again
search('hello'); // Cancelled again
// ... 500ms passes with no more calls
// NOW "Searching for: hello" logs
Throttle: Limit Execution Rate
Throttle ensures a function runs at most once per time period:
function throttle(func, limit) {
let inThrottle; // Closure tracks whether we're in cooldown
return function(...args) {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
The closure here is crucial—each returned function remembers its own timeoutId or inThrottle variable, maintaining state across multiple calls without polluting the global scope.
Key Takeaway: Debounce and throttle use closures to preserve timing state between invocations, enabling sophisticated rate-limiting patterns for event-heavy interactions.