Web VitalsIntermediate
What is debounce? How do you implement a debounce function?
What is Debounce?
Debounce delays a function so that it only runs after N milliseconds have passed without any new calls. Every new call resets the timer.
Idea: run only once things have stopped.
Common use cases
- Search-as-you-type / autocomplete (fire the request once the user stops typing)
- Window
resizethen recompute layout - Live form validation
- Prevent double submissions on a button
Basic implementation
function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
// Reset the timer on every call
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
}
Usage:
const onInput = debounce((e) => {
console.log('search:', e.target.value);
}, 500);
input.addEventListener('input', onInput);
Advanced: leading, trailing and cancel
leading: invoke on the first call immediatelytrailing: invoke after the last call (default)cancel(): cancel a pending invocation
function debounce(fn, delay = 300, { leading = false, trailing = true } = {}) {
let timer = null;
let lastArgs = null;
let lastThis = null;
function invoke() {
fn.apply(lastThis, lastArgs);
lastArgs = lastThis = null;
}
function debounced(...args) {
lastArgs = args;
lastThis = this;
const callNow = leading && !timer;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (trailing && lastArgs) invoke();
}, delay);
if (callNow) invoke();
}
debounced.cancel = () => {
clearTimeout(timer);
timer = null;
lastArgs = lastThis = null;
};
return debounced;
}
Implementation notes
- Use a closure to keep the
timeralive across calls. - Forward
thisand arguments viafn.apply(this, args). - In React, wrap the debounced function in
useRef/useMemoso it is stable across renders.
Debounce vs Throttle
| Debounce | Throttle | |
|---|---|---|
| Strategy | Run after calls stop | Run at most once every N ms |
| Best for | Search, resize, validation | scroll, mousemove, games |
| Analogy | An elevator waiting for the last person | A faucet dripping at a fixed rate |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
