Debounce vs Throttle
Both techniques limit how often a function runs in response to rapid events such as typing, scrolling, or resizing. They differ in when the function runs. Here is how debounce vs throttle compares in practice, and CSS-Tricks has a good visual explanation too.
1. Debounce
Debounce waits until events stop for a given delay, then runs once. Every new event resets the timer.
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const search = debounce((q) => fetchResults(q), 300);
input.addEventListener('input', (e) => search(e.target.value));
If the user types continuously for 2 seconds, the search runs once, 300ms after the last keystroke.
2. Throttle
Throttle runs the function at most once per interval while events keep firing.
function throttle(fn, interval) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
window.addEventListener('scroll', throttle(updateProgressBar, 100));
During 2 seconds of continuous scrolling, updateProgressBar runs about 20 times at a steady... premium content.
