Debounce or throttle, on a timeline
By the end you will see exactly when debounce, throttle and requestAnimationFrame call your code, measured in your own browser, and you will leave with code and a coding-agent prompt built from the values you tuned.
One timeline, three lanes
Debounce waits until events stop for a set time, then runs your function once with the last value. Throttle runs your function at most once per interval for as long as events keep coming. Use debounce when only the final value matters, as in a search box. Use throttle when you need steady updates during the activity, such as a scroll position.
Both are wrappers. You give them a function and a wait, and they return a new function that decides when the original runs. The browser still fires every event. The wrapper only filters the calls you make in response.
raw events: 0 · debounced calls: 0 · throttled calls: 0</> Your tuned values as code. It rewrites itself as you tune.Show code
import { debounce, throttle } from 'lodash-es';
// Final value only: runs once, 300 ms after the last input
const search = debounce(runSearch, 300, { leading: false, trailing: true });
// Steady pace: at most once every 200 ms, both edges on
const onScroll = throttle(trackScroll, 200);
// Autosave: after a 400 ms pause, or every 1000 ms at the latest
const save = debounce(saveDraft, 400, { maxWait: 1000 });
input.addEventListener('input', e => search(e.target.value));
window.addEventListener('scroll', onScroll, { passive: true });
editor.addEventListener('input', save);</> A prompt for your coding agent, with your choices.Show code
Move a slider to build the prompt.
On a touchscreen, drag a finger inside the pad. The pad keeps that gesture, so touch outside it to scroll the page.
Type a word, then stop. Each key press adds a gray tick to the top lane. The debounce lane stays empty while you type and drops one dot after you pause. The throttle lane drops dots at a steady beat while you type and stops soon after you do. Then move the pointer in circles over the pad. Raw events pile up, throttle keeps its beat, and debounce waits until your hand is still.
Drag the sliders and try again. A longer debounce needs a longer pause. A longer throttle spaces the dots further apart. Neither slider changes how many events the browser sends. The code under the panel rewrites itself with your values, and the prompt turns them into instructions for a coding agent. Both also pick up the edges and the maxWait you choose in section 4, so come back and copy them after you have tried those.
One level deeper. Both wrappers run on timers, and a timer callback is a task, like a click handler. It runs only when the main thread is free, so a 300 ms wait means at least 300 ms. Each debounced call also clears one timer and sets another. That is cheap next to a network request or a layout read, but it is not free, so wrap the expensive work, not a single assignment. If you ask for reduced motion, these lanes redraw only when something happens instead of scrolling all the time.
Debounce waits for quiet
A debounce keeps restarting one timer. Each new event cancels the waiting timer and starts a fresh one. Your function runs only when a timer lasts the full wait, and that happens only once the events stop.
</> A trailing debounce is one timer that keeps restarting.Show code
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
const search = debounce(query => fetchResults(query), 300);
input.addEventListener('input', () => search(input.value));A search box is the classic case. Every key press changes the query, but only the query the person finishes typing is worth sending. The demo sends simulated requests to a local list of fruit. Nothing leaves your browser.
no limit: 0 requestsdebounce 300 ms: 0 requeststhrottle 300 ms: 0 requestsRequests are simulated with a local list and a 120 ms delay. Only the debounced results appear under the box. Clearing the box resets the counters.
Type strawberry at your normal speed. The line under the box repeats each letter at once, because feedback is never delayed. With no limit, every key press is a request. Throttle sends a few half-typed queries. Debounce sends one, for the word you meant. To compare on equal terms, press Type strawberry. It clears the box and types the word at a steady 150 ms per letter.
What the counters say. A run ends at 10 requests with no limit, 6 with throttle and 1 with debounce, and the numbers follow from the timing. Debounce sends one because a 150 ms gap never reaches 300 ms. Throttle runs on the first letter, then once at the end of each 300 ms window. Ten letters span 1.35 seconds, so five windows close with a new letter waiting: 1 + 5 = 6. While building this I hit a tie. The throttle timer and the next letter are due at almost the same instant at each window boundary. Which one runs first changes the half-typed word that gets sent, st or str, but never the count. Now type slower than one letter per 300 ms and watch debounce send every letter too. It protects you from fast typists, not slow ones.
Debounce does not fix slow responses. A request for "straw" can still come back after the one for "strawberry". Ignore stale responses with a request counter, as this demo does, or cancel them with an AbortController.
Debouncing helps screen reader users too. The results line is an aria-live="polite" region, which is announced whenever it changes. The waiting and sending status sits outside it on purpose, so each pause produces one announcement: the results.
The trap that bites in React. Call debounce() in a component body and every render creates a new wrapper with its own timer. Each key press renders, so each letter gets its own wrapper and its own delayed request. Nothing is debounced. Create the wrapper once, pass the value in so it never reads stale state, and cancel it on unmount. These demos hit the plain JavaScript version of the same bug. Moving a slider rebuilds the wrappers, and until I called cancel() on the old one, its pending timer still fired and dropped a stray dot after the change.
</> One debounce per component, cancelled on unmount.Show code
// runSearch lives outside the component, so it never changes
function Search() {
const [q, setQ] = useState('');
// Wrong: debounce(runSearch, 300) here makes a new timer every render
const search = useMemo(() => debounce(runSearch, 300), []);
useEffect(() => () => search.cancel(), [search]);
const onChange = e => {
setQ(e.target.value); // the echo stays instant
search(e.target.value); // pass the value; never read q inside runSearch
};
return <input value={q} onChange={onChange} />;
}Throttle keeps a beat
A throttle opens a window each time it runs. Events that arrive while the window is open are held back, and only the newest is kept. When the window closes, the throttle runs once more with that newest event and opens the next window. When events stop, the windows stop too.
raw events: 0 · throttled calls: 0pointermove events per frame in your browser: move over the pad to measureTesting for getCoalescedEvents…On a touchscreen, draw with a finger inside the pad. Touch outside it to scroll. Arrow-key moves are not counted in the per-frame numbers.
Move the pointer across the pad. The thin gray line connects every pointer event. The teal dots are the only positions the throttled function ever saw, and the ring is where it thinks your pointer is now. Raise the interval and the ring jumps along behind your hand. Lower it and the dots crowd onto the line.
</> A throttle with a leading and a trailing call.Show code
function throttle(fn, wait) {
let timer = 0, pending = null;
const tick = () => {
if (!pending) { timer = 0; return; }
fn(...pending); // trailing call with the newest event
pending = null;
timer = setTimeout(tick, wait);
};
return (...args) => {
if (timer) { pending = args; return; }
fn(...args); // leading call
timer = setTimeout(tick, wait);
};
}One level deeper. Browsers do not promise one pointermove per hardware sample, and engines differ, so the panel measures yours. The second readout counts the pointermove events that arrive between two animation frames. A result close to 1.0 means your browser lines continuous input up with frames and merges the samples in between into one event. A result well above 1 means events reach the page closer to when the hardware reports them. Merged samples are not lost. Where it is supported, event.getCoalescedEvents() returns them, and the third readout averages how many each event carries. Many ordinary mice report about 125 times a second, so with frame-aligned events on a 60 Hz screen you would expect about two samples per event. A drawing tool needs all of them. A throttled handler, by design, wants fewer.
Edges and deadlines
A burst of events has two edges: the first event, and the moment the events stop. A wrapper can call your function at either edge, at both, or at neither. Most posts show one default, and that is how people end up with a missing first call or a surprise extra one.
leading off, trailing on · press Send a burstoptions: { leading: false, trailing: true }Peach dots are leading calls. Accent dots are trailing calls. Both wrappers use a 300 ms wait.
Press Send a burst. It sends ten events, 80 ms apart, into both wrappers. With trailing only, debounce calls once, 300 ms after the last event. Turn on Leading and it also calls on the first event, so the person gets an instant response and the final value. Turn off Trailing and debounce calls only at the start, then ignores everything until there is a quiet gap. For throttle, trailing is what keeps the last event. Without it, the final position of a scroll or a drag can be lost. With both edges on, a single event causes only one call, because the trailing call needs a second event. With both off, nothing ever runs.
The second readout is the lodash options object for your switches, and Copy options copies both calls. The code and the prompt in section 1 follow along. Holding an arrow key creates the same kind of burst through key repeat, at a rate set by the operating system, so give keyboard users the same edges.
</> A leading-only lodash debounce stops double submits.Show code
import { debounce } from 'lodash-es';
// Run on the first click, ignore repeats until 1 s of quiet
const submitOnce = debounce(sendOrder, 1000, {
leading: true,
trailing: false
});
button.addEventListener('click', submitOnce);Debounce has one more weakness: some activity never goes quiet. Someone typing a long paragraph without stopping can hold off a debounce forever. maxWait adds a deadline. If the function has not run for that long, it runs anyway, and then the debounce carries on as before.
0 events · plain debounce: 0 calls · with maxWait: 0 callsdebounce(saveDraft, 400, { maxWait: 1000 })Peach dots are calls forced by maxWait. Teal dots are normal trailing calls. Both debounces wait 400 ms.
Press and hold Hold to stream, or focus it and hold Space. It sends an event every 60 ms. The plain debounce lane stays empty for as long as you hold. The maxWait lane drops a peach dot at each deadline, then a teal trailing dot after you let go. Making this button work on a phone took three fixes. A long press opened the context menu and cancelled the pointer, so the button now blocks the menu, sets touch-action: none and captures the pointer.
This is the right shape for autosave: save after a pause, but never let a long session go unsaved. A save you can see land shows how to make that save visible. With maxWait, debounce and throttle turn out to be the same machine. lodash builds throttle as a debounce with both edges on and a maxWait equal to the wait.
</> maxWait in lodash, and what throttle really is.Show code
import { debounce, throttle } from 'lodash-es';
// Save after a 400 ms pause, and at least once a second while typing
const save = debounce(saveDraft, 400, { maxWait: 1000 });
editor.addEventListener('input', save);
// These two behave the same way
const a = throttle(updateProgress, 200);
const b = debounce(updateProgress, 200, { leading: true, maxWait: 200 });Frames beat 16 milliseconds
For anything visual, such as moving a handle or filling a progress bar, the right update rate is the screen's refresh rate. People often write throttle(fn, 16) to get about 60 updates a second. That has two problems. Many screens refresh faster than 60 times a second. And a timer has no idea when the next frame is.
requestAnimationFrame (rAF) solves both. It runs your callback just before the browser draws the next frame, at whatever rate the screen refreshes. You store the newest position in the event handler and apply it once, inside the frame callback.
throttle(16): 0 of 0 frames showed an old position · 0 updates overwritten before paintrequestAnimationFrame: 0 writes in 0 frames · move to measure frame timeThe strip shows the last 250 ms of movement. Lines are frames. Teal dots are throttle(16) updates that a frame painted. Peach dots were overwritten before any frame drew them. A shaded stretch is a frame that painted an old position.
Drag across the pad. Both handles follow the same pointer. On every frame with movement, the demo checks the throttled handle just before the browser paints. The first readout counts frames that still showed an older position, and updates that were replaced before any frame drew them. The rAF handle writes once per frame by design, so its readout measures how long your frames actually are.
The strip shows what the counters only sum up. Each line is a frame, placed where its rAF callback ran. Each dot is a throttle update, placed where its timer fired. Two dots between two lines means wasted work. No dot before a shaded line means a stale frame. When you stop, the strip freezes so you can read it. Then press Simulate a 250 Hz mouse. It feeds a new position about every 4 ms for two seconds, like a mouse with a high polling rate, and the rAF handle stays on the newest one.
What to expect, and the trap I hit. On a 60 Hz screen, the timer and the frames run at almost the same rate, so the strip is mostly one teal dot per frame. Every so often the timer slides across a frame boundary, and you get a peach dot or a shaded frame. How often depends on timer jitter, and that is the point: you cannot schedule it away. On a 120 Hz screen a frame lasts 8.3 ms, so a 16 ms throttle can update at most every second frame, and roughly half of the frames with movement show an old position. Your counters check that arithmetic on your hardware. My first version checked for old positions from a timer, and the numbers jumped around, because a timer can land on either side of a paint. The check has to run inside the rAF callback.
</> Store the newest value, apply it once per frame.Show code
let latestX = 0, queued = false;
pad.addEventListener('pointermove', event => {
latestX = event.clientX;
if (queued) return;
queued = true;
requestAnimationFrame(() => {
queued = false;
handle.style.transform = `translateX(${latestX}px)`;
});
});On a phone, drag sideways inside the pad. Vertical swipes still scroll the page. The drag uses pointer capture, as in Sliders that fight back, and moves the handles with transform only. With reduced motion, the simulation makes one slow sweep instead of swinging back and forth.
One level deeper. On each frame, the browser runs the rAF callbacks, then recalculates styles, lays out the page and paints. No timer can run between those callbacks and the paint, which is why a check from a frame callback knows what will be drawn. Timer callbacks run between frames, wherever they happen to land, which is the drift you see in the strip. Browsers also pause rAF in background tabs, while timers there keep running at a slower rate.
A rule for each event
Choose by asking what the person needs: the final value, a steady stream of values, or a value on every frame.
- Search box, filters, form validation: debounce on the trailing edge, with a wait of a few hundred milliseconds. Ignore or abort stale responses.
- Autosave: debounce with
maxWait, so long typing sessions still save. - Submit and other action buttons: a leading-only debounce, plus disabling the button while the request runs.
- Resize: for visual adjustments, use CSS first, then rAF. For expensive work, such as redrawing a chart, debounce. When you care about one element rather than the window, use
ResizeObserver. - Scroll: for visual effects, use rAF, or
IntersectionObserverwhen you only need to know what is visible. For analytics or loading the next page, throttle with the trailing edge on. For knowing when scrolling has stopped, see the panel below. - Drag and hover effects: rAF, never debounce. A debounced drag handle does not move until the hand stops.
Knowing when scrolling has stopped is the one job where debounce has a native rival. The scrollend event fires when a scroll has finished, and that includes the person lifting their finger. The panel tests 'onscrollend' in window in your browser, prints the answer, and then races the two signals.
Testing for scrollend…Scroll the box to measure.Scroll the box with a wheel, a trackpad, the keyboard or a finger, then stop. The readout measures how long after the last scroll event each signal fired. The debounce can never beat its own wait, so it always reports at least the slider value. On a touchscreen, try the case that separates them. Drag the list, then hold your finger still without lifting it. The debounce declares the scroll over after its wait, and the readout counts every false stop. scrollend waits until you lift your finger, because the gesture has not finished. Scroll by script runs a smooth scrollTo(), or an instant one if you ask for reduced motion, so you can compare the signals without your hand in the loop.
</> Use scrollend where it exists, debounce where it does not.Show code
function onScrollStop(el, fn, wait = 150) {
if ('onscrollend' in window) {
el.addEventListener('scrollend', fn);
return;
}
let timer;
el.addEventListener('scroll', () => {
clearTimeout(timer);
timer = setTimeout(fn, wait);
}, { passive: true });
}Sometimes you need none of this. If the work is cheap, such as setting one transform, a wrapper only adds delay, so measure before you wrap. Never limit the feedback itself: key echo, focus rings and a button's pressed state must react at once. Limit the expensive consequence, not the response the person is waiting to see. Whichever wrapper you pick, create it once, cancel it on teardown, and check that keyboard users get the same edges as pointer users. The code and prompt in section 1 already hold the values you tuned on this page.
Keep reading: IntersectionObserver instead of a throttled scroll listener
Quick answers
What is the difference between debounce and throttle?
Debounce waits until events stop for a set time, then runs your function once with the latest value. Throttle runs your function at most once per interval for as long as events keep coming. Use debounce when only the final value matters, as in a search box. Use throttle when you need steady updates during the activity, such as tracking a scroll position.
Should I use debounce or throttle for scroll and resize?
For visual scroll effects, use requestAnimationFrame, or IntersectionObserver when you only need to know what is visible. For analytics or loading the next page, throttle with the trailing edge on. For resize, handle visual changes with CSS first, then rAF, and debounce expensive work like redrawing a chart. Use ResizeObserver when you care about one element rather than the window.
What do leading and trailing mean in debounce and throttle?
A burst of events has two edges: the first event and the moment the events stop. A leading call runs on the first event, so the person gets an instant response. A trailing call runs after the burst, with the final value. With both edges on, a single event causes only one call. The trailing call happens only if more events arrived after the leading one.
What does maxWait do in a debounce?
maxWait gives debounce a deadline. If the function has not run for that long, it runs anyway, even while events keep coming, and then the debounce carries on as before. This suits autosave: save after a pause, but also at regular intervals during long typing sessions. In lodash, throttle is built as a debounce with both edges on and a maxWait equal to the wait.
Is requestAnimationFrame better than throttle(fn, 16) for animations?
For anything drawn on screen, yes. A 16 ms timer does not know when the next frame is, and many screens refresh faster than 60 times a second. requestAnimationFrame runs your callback just before the browser draws the next frame, at the screen's refresh rate. Store the newest pointer position in the event handler and apply it once per frame, so the handle never shows an old position.