4 min read
•Question 17 of 50mediumWhat are Debounce and Throttle?
Understanding rate-limiting function techniques.
What You'll Learn
- Difference between debounce and throttle
- Implementation
- Use cases
Comparison
| Technique | Behavior | Use Case |
|---|---|---|
| Debounce | Execute after delay ends | Search input |
| Throttle | Execute at regular intervals | Scroll events |
Debounce
Executes function only after a specified delay has passed since the last call.
code.jsJavaScript
function debounce(fn, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
}
// Usage
const search = debounce((query) => {
console.log('Searching:', query);
}, 300);
// Typing "hello" quickly
search('h');
search('he');
search('hel');
search('hell');
search('hello');
// Only logs: 'Searching: hello' (after 300ms)Throttle
Executes function at most once per specified time period.
code.jsJavaScript
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// Usage
const handleScroll = throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 100);
window.addEventListener('scroll', handleScroll);
// Logs at most every 100ms while scrolling