Engineering note
Debounce vs Throttle: Which One Your Search Box and Scroll Handler Need
Debounce waits. Throttle paces. Mixing them up costs you API calls. Type into the analyser below, count the requests, then see the one bug neither of them can fix.

Key takeaways
- 01Debounce runs once, after the events stop for a set time. Throttle runs at most once per interval while they keep coming.
- 02A search box that hits the network wants debounce. Autosave too. Scroll, resize and drag want throttle, or requestAnimationFrame for anything that paints.
- 03Debounce cannot stop a request that already left. Give each request an AbortController and abort it in the effect cleanup.
- 04For AI chat, block double sends and add a Stop button. Debounce only the as-you-type extras.
- 05If filtering is local, debounce just adds lag. If rendering is the slow part, try useDeferredValue first.
Type into it first
Debounce waits. Throttle paces. Mixing them up costs you API calls.
The analyser below has three channels. The top one is every input event your browser fires. The middle one is a debounced handler. The bottom one is throttled. Every dot in the bottom two is a request you would pay for.
Type something real, like a search you would actually run, then drag the wait slider to 50 ms and type it again. That is what a 'fast' debounce really means: almost no debounce at all.
I've seen the lag on this site. The header listens to every scroll event, with no throttle, and I've watched it jank.
Count the requests
Type a query or replay a typist. Drag the wait and watch the debounce and throttle channels change.
Debounced requests sent
Nothing yet. Stop typing.
What the wait costs
Type above or press Replay. Hollow rings are calls that are scheduled but have not fired yet.
What is the difference between debounce and throttle?
Debounce runs a function once, after events have stopped for a set time. Throttle runs it at most once per interval while events keep coming. Debounce asks "is the user done?". Throttle asks "what is happening right now?".
Debounce is a lift door: every new person resets the close timer, and it only leaves once nobody has turned up for a while. Throttle is a metronome that ticks on schedule however loud the room gets.
So the rule is boring, which is why it works. If you only care about the final value, debounce. If you care about the values along the way, throttle. A search box that hits the network wants the final query, while a scroll position wants the whole journey. If the box only filters local data, skip the timer.
Both are one timer plus a closure that remembers it. The timer callback is an ordinary task, and the event loop post shows where it queues, so I will skip that part here.
A debounce hook in 15 lines
In React I debounce the value, not the handler. It fits the way effects already work, and you get cleanup for free.
The cleanup is the whole trick. React runs it with the old values before running the effect again with the new ones, so every keystroke clears the previous timer and no timer outlives a newer keystroke.
I care more about the second half: the same cleanup aborts the request the new query replaced. Hold that thought.
tsx
import { useEffect, useState } from 'react';
// Debounce the value, not the handler.
export function useDebouncedValue<T>(value: T, wait = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), wait);
return () => clearTimeout(id); // a newer value cancels this timer
}, [value, wait]);
return debounced;
}
// Usage: debounce the query, abort the request it replaced.
const q = useDebouncedValue(query, 300);
useEffect(() => {
if (!q) return;
const ctrl = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal: ctrl.signal })
.then((res) => res.json())
.then(setResults)
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});
return () => ctrl.abort(); // runs before the next query's request
}, [q]);A throttle hook that keeps the last event
Throttle is where hand-rolled versions go wrong. The lazy one ignores events inside the window and never looks back. Scroll fast, stop, and your handler is stuck on a position the page left behind.
I always keep a trailing call. The hook below schedules one for the remaining time, so the last event lands even when the user has stopped.
For anything that paints, I would try requestAnimationFrame before any fixed interval. The browser calls it right before the next repaint, usually in step with the display refresh rate, so you never compute a frame nobody sees.
Sometimes a flag this simple looks cheap. The header on this site flips a scrolled flag from a passive scroll listener, with no throttle. When the value has not changed, React skips the re-render. I have still seen that listener jank, so I measure it now instead of assuming it is free.
tsx
import { useCallback, useEffect, useRef } from 'react';
export function useThrottledCallback<A extends unknown[]>(
fn: (...args: A) => void,
wait = 100
) {
const fnRef = useRef(fn);
const last = useRef(0);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
useEffect(() => { fnRef.current = fn; }, [fn]);
useEffect(() => () => clearTimeout(timer.current), []);
return useCallback((...args: A) => {
const run = () => { last.current = Date.now(); fnRef.current(...args); };
const left = wait - (Date.now() - last.current);
clearTimeout(timer.current);
if (left <= 0) run();
else timer.current = setTimeout(run, left); // keep the trailing call
}, [wait]);
}Break a throttled scroll handler
Scroll the box, then flick back to the top. Turn the trailing call off and do it again.
Scroll the box. Then flick back to the very top, quickly.
The bug debounce cannot fix
Debounce decides when a request starts, and it has no say over one that already left.
Type, pause, type again. Debounce fires twice. If the first request is slower, its answer lands last and overwrites the right one. The user reads results for words they already deleted.
The fix is one AbortController per request. Pass its signal to fetch, and call abort() as soon as a newer request replaces it. The old fetch rejects with an AbortError, which you ignore. In React that is the return () => ctrl.abort() line in the hook above.
Follow one request through the diagram below. Chapter 4 is the one that saves you.
Follow one request, then kill it
Step through the five chapters. Number 4 is where AbortController earns its place.
Pick a chapter on the rail to follow one request, or watch the packets loop.
Should you debounce an AI chat input?
Not the send button. Debounce a chat input only for as-you-type features, like suggestions or a token counter. For sending, block double submits and give the user a Stop button wired to an AbortController.
AI requests flip the usual maths. A search API answers quickly, while a model reply can stream for seconds. The expensive part is not starting a request but letting one you no longer need keep streaming.
My rule: debounce what the user is still typing, abort what the user has replaced. Pass the signal from your route handler to the upstream model call as well. Otherwise you may only have stopped listening, while the work carries on.
Abort alone is not enough either. Without the timer, every keystroke starts a request and cancels the last one, so the answer is right and your rate limiter is furious. Run the race below in all three modes.
The chatbot on this site already blocks double sends: the input is disabled while a reply loads. It has no AbortController and no Stop button.
Race two AI requests
Guess which answer ends up on screen, then compare debounce only, debounce plus abort, and abort only.
Predict first. The user types “summarise my”, pauses, then finishes “summarise my last PR”. With debounce only, which answer is on screen at the end?
grey: waiting for the first token · red: stale query streaming · green: the live query · ×: aborted
0
requests started
0
aborted
0
stale tokens streamed
On screen
Make a guess, then run the race.
Latencies and the 40 tokens a second are made up for the demo
Do you still need lodash debounce?
Not for the two hooks above. Keep lodash, or a small library, when you need leading-edge calls, maxWait, or cancel and flush on a function shared across components.
Here is what the library gives you that 15 lines do not:
- `leading: true` fires on the first event instead of the last. Good for a button that should feel instant.
- `maxWait` caps how long debounce may wait. Autosave wants this, or a fast typist never saves.
- `cancel()` drops the pending call and `flush()` runs it now. Handy on unmount or route change.
- lodash `throttle` is leading and trailing by default, and in the source it is literally debounce with `maxWait` set to the wait.
- If rendering is the slow part, try `useDeferredValue` first. It has no fixed delay and adapts to the device, but it does not reduce network requests.
- `scheduler.yield()` helps long tasks hand the main thread back. MDN still marks it as limited availability, so feature-check it.
Services
Need help implementing this?
I build these systems for a living - let's work on yours.
Frontend Development
Production UIs in React, Next.js, or Vue- third-party and payment integrations included. Built for real traffic and maintained in production.
Full Stack Development
End-to-end apps: MERN, React+Node, or MEVN, plus React Native for mobile. Auth, role-based access, and real-time where it matters. Designed to scale without rewrites.
Frontend Architecture & System Design
Structure so teams can ship. Clear boundaries, state strategy, and contracts. New features land cleanly; refactors stay low-risk.
FAQ
Questions people ask
What is the difference between debounce and throttle?
Debounce runs a function once, after events have stopped for a set time. Throttle runs it at most once per interval while events keep coming. Use debounce when only the final value matters, such as a search query, and throttle when the values along the way matter, such as scroll position.
Should I debounce a search input in React?
Debounce it when each query hits the network. Debounce the value with a small hook, start around 300 ms and tune it by typing for real. If the search filters local data, skip debounce; it just adds lag. If rendering the results is slow, try useDeferredValue.
How do I cancel a fetch request in React?
Create an AbortController inside the effect that starts the fetch, pass controller.signal to fetch, and return a cleanup function that calls controller.abort(). React runs the cleanup before the effect runs again, so a newer query cancels the older request. Ignore the AbortError it rejects with.
Should I debounce an AI chat input?
Not the send action. Block double submits and add a Stop button that calls abort() on an AbortController. Debounce only as-you-type features such as suggestions, and abort any in-flight request that a newer input replaces.
Do I need lodash for debounce and throttle?
Not for simple cases. A debounce or throttle hook fits in about 15 lines. Lodash is still worth it when you need leading-edge calls, maxWait, or cancel and flush on a shared function.
Your turn
- >Did this help you ship something?
- >Which part clicked the most for you?
- >Applying this at work? Share your experience.
Continue
More engineering notes
How JavaScript Actually Executes Your Code: Event Loop & Call Stack Deep Dive
JavaScript call stack, event loop, microtask queue, and macrotask queue explained with real execution traces. Learn why Promises beat setTimeout and how to debug async timing bugs.
PerformanceImproving Next.js Lighthouse Without Killing the Design
How I chase Lighthouse and Core Web Vitals on a real Next.js portfolio without turning the UI into a gray wireframe.
Discussion
Leave a comment
Thoughts, questions, corrections - all welcome.