Throttle & Debounce
High-frequency events like scroll, resize, and input can fire hundreds of times per second. Throttle and debounce are two essential techniques to limit how often your handlers run, improving performance and reducing unnecessary API calls.
What is the difference between debounce and throttle?
Both limit how often a function runs during rapid events. Debounce waits until the events stop for a set time, then runs once; it's ideal for search-as-you-type. Throttle runs at most once per interval while events keep firing; it's ideal for scroll and resize handlers.
function debounce(fn, ms) {
let t;
return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
function throttle(fn, ms) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= ms) { last = now; fn(...args); }
};
}
input.addEventListener("input", debounce(search, 300));Debounce — Wait for silence
Output: ─ ─ ─ ─ ─ ─ ─ C ─ ─ ─ ─ ─ D ─
↑ fires after 400ms of silence
Throttle — Rate limiter
Output: ─ A ─ ─ ─ C ─ ─ ─ E ─ ─ ─ G ─
↑ fires every 200ms max
Real-world Use Cases
Only call the API after the user stops typing (400ms silence)
Save to server 1s after the user stops making changes
Recalculate layout 200ms after resize ends, not on every pixel
Update sticky header position at most every 100ms
Track cursor/drag position at most every 16ms (1 frame)
Prevent form double-submission by throttling to once per 1s
Common Pitfalls
Interactive Demo
Code Editor
<input id="search" placeholder="Type fast...">
<p>Raw input events: <b id="raw">0</b></p>
<p>Debounced (300ms after you stop): <b id="deb">0</b></p>
<p>Throttled (max once per 500ms): <b id="thr">0</b></p>Preview
Throttle and debounce — step by step
Throttle — execute at most once per interval
Throttle ensures a function fires at most once every N milliseconds, no matter how many times it is called. On scroll or mousemove events that fire hundreds of times per second, throttle keeps execution predictable. The first call fires immediately; subsequent calls within the window are dropped.
🎯 Quick Check
A search input fires an API call on every keystroke. Which technique should you use?
Throttle and Debounce: summary
Key points
- Debounce: "wait for a pause". Throttle: "no more than once every X ms".
- A 200–300ms debounce feels responsive for search inputs.
- For visual updates on scroll,
requestAnimationFrameis often better than throttle.
Frequently asked questions
›When should I use debounce?
When you only care about the final value after the user stops: search suggestions, form auto-save, and recalculating on resize end.