Topic F5
Debounce and throttle
Waiting for the user to stop, or capping how often: for events that fire in bursts.
Watch: count the green blocks in the front row. Each one is a time the site asks the server. Fewer means less work for the server.
- happening now
- letters already typed
- a question to the server
Like a lift and a traffic light
- Debounce is like lift doors: every time someone steps in, the doors wait again. The lift only leaves after a few seconds with nobody stepping in.
- Throttle is like a traffic light: however many cars arrive, it turns green at most once per cycle.
Code, for programmersBoth in a few lines
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer); // every call resets the wait
timer = setTimeout(() => fn(...args), wait);
};
}
function throttle(fn, gap) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= gap) { last = now; fn(...args); } // otherwise drop it
};
}
input.addEventListener("input", debounce((e) => search(e.target.value), 300));
window.addEventListener("scroll", throttle(updateProgressBar, 100));The throttle above only fires at the start (leading). The full version (like lodash.throttle) also makes one last call at the end (trailing), so the final value is never missed.
Which to use
| Case | Choose |
|---|---|
| Search as you type, username checks | debounce (200–400 ms) |
| Autosaving a draft | debounce (1–2 s), plus save when the tab closes |
| Scroll, resize, drag, mouse moves | throttle, or requestAnimationFrame |
| A pay button clicked twice | disable the button + an idempotency key on the server |
Quiz
A user types 10 letters quickly without pausing, with a 300 ms debounce. How many requests?
To update a progress bar while scrolling, which fits better?
What's the weakness of a leading-only throttle?
0 of 3 answered.