Debounce vs Throttle in JavaScript: What's the Difference?
Debounce and throttle are two ways to limit how often a function runs when an event fires many times in a row. Debounce waits until the events stop for a set time and then runs the function once. Throttle lets the function run at most once per time interval while the events keep coming.
They sound similar, and interviewers love asking about them for exactly that reason. Let's start with the problem they solve, then see how each one behaves.
The problem: events fire very often
Some browser events fire a lot. Typing fires one event per key. Scrolling and resizing can fire many times per second. Now imagine this handler:
input.addEventListener("input", (event) => {
fetch(`/api/search?q=${event.target.value}`);
});
If someone types "javascript", that's 10 requests in a couple of seconds. Nine of them are for half-typed words nobody cares about. They waste bandwidth, hit your server, and the answers may even arrive out of order.
We need a way to say "don't run this on every event". Debounce and throttle are two different answers to that.
Debounce: wait for the pause
Think of an elevator door. When someone walks in, the door waits a few seconds before closing. If another person arrives, the timer starts over. The door only closes after nobody has come in for a while.
Debounce works the same way:
- An event happens, so we start a timer.
- If another event happens before the timer ends, we cancel the timer and start a new one.
- When the timer finally ends without interruption, the function runs once.
Here is a minimal version:
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer); // cancel the previous timer
timer = setTimeout(() => {
fn.apply(this, args); // run after the pause
}, delay);
};
}
const search = debounce((query) => {
fetch(`/api/search?q=${query}`);
}, 300);
input.addEventListener("input", (event) => search(event.target.value));
How does timer survive between calls? It lives in the closure of the returned function: each call sees the same timer variable. If closures are new to you, read the closure question first.
Now typing "javascript" fast sends one request, 300 ms after the last key.
Throttle: limit the rate
Think of a water tap that only lets one drop fall per second, however hard you push the handle. Throttle works like that:
- The first event runs the function right away.
- Any events during the next interval are ignored.
- When the interval is over, the next event is allowed through.
function throttle(fn, interval) {
let lastRun = 0;
return function (...args) {
const now = Date.now();
if (now - lastRun >= interval) {
lastRun = now;
fn.apply(this, args);
}
};
}
const onScroll = throttle(() => {
console.log("scroll position:", window.scrollY);
}, 200);
window.addEventListener("scroll", onScroll);
While the user scrolls for 2 seconds, onScroll logs about 10 times instead of hundreds. The function keeps running during the scroll, just at a calm pace.
Debounce vs throttle side by side
| Debounce | Throttle | |
|---|---|---|
| Runs when | Events have stopped for the delay | At most once per interval |
| During a long burst of events | Nothing runs until it ends | Runs regularly |
| Number of calls for a 3 s burst, 500 ms limit | 1 | About 6 |
| Best when | Only the final value matters | You need regular updates |
| Typical uses | Search box, autosave, field validation | Scroll, resize, mousemove, drag |
A quick way to remember it: debounce asks "have they finished?" and throttle asks "has enough time passed?".
Leading and trailing edges
Both techniques can fire at two moments:
- The leading edge is the start of the burst.
- The trailing edge is the end of it.
My simple debounce runs on the trailing edge only. A "leading" debounce runs immediately on the first event and then ignores the rest until things go quiet. That's handy for a "Submit" button: the first click goes through and accidental double-clicks are ignored.
My simple throttle runs on the leading edge, so the last event of a burst can be dropped. Libraries such as Lodash expose leading and trailing options for both, so you can choose. According to the Lodash docs, _.debounce defaults to trailing only, and _.throttle defaults to both.
Debounce in React
In React, the common pattern is to debounce a value instead of a function. This hook delays updating a value until it stops changing:
import { useEffect, useState } from "react";
function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id); // cleanup restarts the timer
}, [value, delay]);
return debounced;
}
function Search() {
const [text, setText] = useState("");
const query = useDebouncedValue(text, 300);
useEffect(() => {
if (!query) return;
const controller = new AbortController();
fetch(`/api/search?q=${query}`, { signal: controller.signal });
return () => controller.abort();
}, [query]);
return <input value={text} onChange={(e) => setText(e.target.value)} />;
}
The input updates instantly because it uses text. The request only uses query, which settles 300 ms after the last keystroke. The cleanup function does the "cancel the previous timer" job from our plain debounce. If cleanups are unfamiliar, see useEffect cleanup.
A common bug is creating the debounced function inside a component body without memoizing it. Each render makes a fresh function with a fresh timer, so nothing is ever debounced. Create it once, for example with useMemo, or debounce the value as shown above.
Examples
1. A search box that spams the server
Problem: every keystroke sends a request, and slow responses can overwrite newer ones.
Why: the handler runs once per input event.
Fix: debounce the handler by about 300 ms. Cancel the in-flight request with AbortController if you want to be extra safe.
2. A scroll handler that makes the page janky
Problem: a handler that measures the page runs hundreds of times while scrolling.
Why: scroll events fire continuously and the handler does real work each time.
Fix: throttle it, for example to once every 100-200 ms. Debounce would be wrong here, because the UI would freeze until the user stops scrolling.
3. An infinite-scroll "load more" check
Problem: the page checks "is the user near the bottom?" on every scroll event.
Fix: throttle the check. If you only need to know when a sentinel element becomes visible, IntersectionObserver is an even better tool, because the browser does the watching for you.
4. A debounce that never fires
Problem: a live-updating chart is debounced by 1 second, but data arrives every 500 ms, so it never redraws.
Why: each event restarts the timer before it can finish.
Fix: use throttle, or a debounce with a maxWait.
Don't reach for these every time
- To know when scrolling finished, MDN points to the
scrollendevent rather than debouncingscroll. - Don't use
requestAnimationFrameas a replacement for a throttle on scroll. MDN says it doesn't help there, because animation frames fire at about the same rate as scroll events. Use a timer-based throttle instead. - For animations,
requestAnimationFrameor CSS is usually the right tool.
Interview answer
Debounce and throttle both limit how often a function runs during rapid events. Debounce delays the call until the events have stopped for a given time, so it runs once at the end, which is ideal for search inputs and autosave. Throttle guarantees the function runs at most once per interval, so it keeps running at a steady pace, which is ideal for scroll and resize handlers. Both are built with closures that hold a timer or a timestamp.
Summary
- Both techniques limit how often a function runs when an event fires many times.
- Debounce runs the function once, after events have stopped for the delay.
- Throttle runs the function at most once per interval, during the burst.
- Debounce = "wait for the pause". Throttle = "limit the rate".
- Use debounce when only the final value matters (search, autosave, validation).
- Use throttle when you need regular updates (scroll, resize, drag, mousemove).
- Both are built with a closure that keeps a timer (debounce) or a timestamp (throttle).
- A plain debounce can starve if events never pause. Use
maxWaitor throttle. - Leading edge fires at the start of a burst, trailing edge at the end.
- In React, debounce a value with a hook, and never recreate the debounced function on every render.
- Prefer
scrollendorIntersectionObserverwhen they fit the job better.