Throttle and Debounce Decorators
You'll learn how to create decorators that control how frequently methods can be invoked, preventing performance issues from excessive calls.
Why Rate-Limiting Matters
Imagine a search input that triggers an API call on every keystroke. Without rate-limiting, typing "javascript" would fire 10 separate requests! Throttle limits execution to once per time period (like "maximum once every 500ms"), while debounce waits for activity to stop before executing (like "only after the user stops typing for 300ms").
Creating a Throttle Decorator
function throttle(delay) {
return function(target, context) {
let lastCall = 0;
const original = target;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return original.apply(this, args);
}
};
};
}
class ScrollHandler {
@throttle(300)
handleScroll(event) {
console.log('Scroll handled at', Date.now());
// Expensive calculation
}
}
Creating a Debounce Decorator
function debounce(delay) {
return function(target, context) {
let timeoutId;
const original = target;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
original.apply(this, args);
}, delay);
};
};
}
class SearchBox {
@debounce(500)
search(query) {
console.log('Searching for:', query);
// API call happens only after user stops typing
}
}
When to Use Which
Use throttle for continuous events where you want regular updates (scroll, resize, mouse movement). Use debounce for actions that should only happen after the user finishes their activity (search input, form validation, window resize completion).
Key Takeaway: Throttle and debounce decorators wrap methods with rate-limiting logic, controlling execution frequency to improve performance and user experience without cluttering your class logic with timing code.