**Debounce** waits for a quiet period — useful for search-as-you-type (fire API call only after user stops typing). **Throttle** limits execution rate — useful for scroll/resize handlers (run at most once per 100ms). Both are essential for performance optimization when dealing with high-frequency events.
1Understanding Debounce & Throttle
Debounce waits for a quiet period — useful for search-as-you-type (fire API call only after user stops typing). Throttle limits execution rate — useful for scroll/resize handlers (run at most once per 100ms). Both are essential for performance optimization when dealing with high-frequency events.
Use debounce for 'wait until done' (search input). Use throttle for 'limit rate' (scroll, resize, mouse move).
// Debounce implementation
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// Search input fires only 300ms after typing stops
const searchInput = document.querySelector('#search');
searchInput.addEventListener('input', debounce((e) => {
fetchResults(e.target.value);
}, 300));2Practical Example
Here is a real-world application of Debounce & Throttle showing how it is used in production JavaScript code.
// Throttle implementation
function throttle(fn, interval) {
let last = 0;
return function(...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
// Scroll handler fires at most 10 times per second
window.addEventListener('scroll', throttle(() => {
updateScrollIndicator();
}, 100));3Best Practices
Follow these guidelines when working with Debounce & Throttle:
1. Use debounce for search inputs, form validation, resize handlers
2. Use throttle for scroll events, infinite scroll, rate-limited APIs
3. Always clean up debounced/throttled timers on component unmount
Tip: Use debounce for 'wait until done' (search input). Use throttle for 'limit rate' (scroll, resize, mouse move).
// Debounce implementation
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// Search input fires only 300ms after typing stops
const searchInput = document.querySelector('#search');
searchInput.addEventListener('input', debounce((e) => {
fetchResults(e.target.value);
}, 300));