JavaScriptMedium
Debounce vs Throttle use cases?
Use debounce when only the final value after a burst matters (search input, autosave, resize-end), and throttle when you need regular updates while events keep firing (scroll position, drag, pointer tracking, rate-limited actions).
Debounce: "wait until they stop"
- Search-as-you-type: send one request after the user pauses typing.
- Form validation: validate a username after typing stops.
- Autosave drafts: save a second after the last edit.
- Window resize end: recalculate an expensive layout once resizing stops.
- Leading debounce for buttons: act on the first click and ignore rapid repeats (prevent double submit).
Throttle: "at most every N ms"
- Scroll handlers: update a progress bar or sticky header while scrolling.
- Infinite scroll checks (though
IntersectionObserveris better). - Drag and drop, drawing apps, pointer tracking.
- Live resize previews.
- Rate-limited APIs or analytics: send position or presence updates every second.
- Game input like firing at a fixed rate.
Visualising the difference
Events: | | | | | | | | | (continuous for 2 seconds)
- Throttle (500 ms):
| | | | |runs regularly during the burst. - Debounce (500 ms):
|runs once, after the burst.
Other tools
requestAnimationFramefor visual updates (at most once per frame).IntersectionObserverinstead of scroll handlers for visibility.AbortControllerto cancel stale requests, which is still needed with debounce when responses arrive out of order.
Code example
js
1function debounce(fn, ms) {2 let t;3 return (...a) => {4 clearTimeout(t);5 t = setTimeout(() => fn(...a), ms);6 };7}8function throttle(fn, ms) {9 let last = 0;10 return (...a) => {11 const now = Date.now();12 if (now - last >= ms) {13 last = now;14 fn(...a);15 }16 };17}1819const debounced = [];20const throttled = [];21const onSearch = debounce((q) => debounced.push(q), 50);22const onScroll = throttle((y) => throttled.push(y), 50);2324// Simulate 300ms of continuous events, one every 10ms25for (let i = 1; i <= 30; i++) {26 setTimeout(() => {27 onSearch(`query ${i}`);28 onScroll(i * 10);29 }, i * 10);30}3132await new Promise((r) => setTimeout(r, 450));33console.log("debounce ran", debounced.length, "time(s):", debounced); // 1 time: ["query 30"] - only the final value34console.log("throttle ran", throttled.length, "times:", throttled); // ~6 times, spread through the burst
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.