Debounce & Throttle — JavaScript interview guide
Debounce & Throttle
Debounce waits until calls STOP for a while, then runs once. Throttle runs at most once every X milliseconds while calls keep coming.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
Debounce: only the last call wins
1function debounce(fn, delay) {2let timer;3return (...args) => {4clearTimeout(timer);5timer = setTimeout(() => fn(...args), delay);6};7}8▶const search = debounce(q => console.log("API:", q), 300);1011search("r"); // user types at 0ms12search("re"); // 100ms13search("rea"); // 200ms
| search | ƒ debounced |
| timer | undefined |
| delay | 300 |
empty
Waits until the Call Stack is empty. Microtasks always go first.
empty
empty
nothing printed yet
What happens:debounce returns a new function. Thanks to a closure, every call to search shares the SAME timer variable.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
When to use which
Debounce: search input, autosave, window resize end. Throttle: scroll position, mouse move, infinite scroll checks.
Throttle implementation
Run immediately, then ignore calls until the wait time passes.
function throttle(fn, wait) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn(...args);
}
};
}Remember this
- Both rely on a closure holding a timer or timestamp.
- Debounce can have leading and trailing options.
- Remember to cancel on unmount in React.
Interview questions
Debounce vs throttle in one line?
Debounce: run after the user stops. Throttle: run at a steady maximum rate while the user continues.
Practice
- Add a cancel() method to debounce.
- Write a useDebounce React hook.