In the DOM Events chapter, we attached handlers to events like input, scroll and mousemove. Some of these events fire a lot:
Typing
"javascript"into a search box firesinput10 times, once per letter.Scrolling a page can fire
scrolldozens of times per second.Resizing a window or moving the mouse can fire hundreds of events in a few seconds.
If each event triggers expensive work, like calling a search API, recalculating a layout or saving to a server, your app becomes slow, your server gets flooded, and you may even pay for thousands of useless API calls.
Debouncing and throttling are two simple techniques that control how often a function actually runs. Both are built with closures and setTimeout(), and "implement debounce" is one of the most popular frontend interview questions.
The Two Ideas in One Line Each
Debounce: wait until the events stop for a while, then run the function once.
Throttle: run the function at most once in every fixed time interval, no matter how many events happen.
A simple way to remember them:
Debounce is like a lift (elevator) door. Every time someone new walks in, the door waits again. It only closes when nobody has entered for a few seconds.
Throttle is like a metro train that leaves every 5 minutes. However many people arrive on the platform, a train departs at most once every 5 minutes.
One Tool We Need: clearTimeout()
You already know setTimeout() from the Asynchronous JavaScript chapter. It also returns an ID, and passing that ID to clearTimeout() cancels the timer before it runs:
const timerId = setTimeout(() => {
console.log("This will never print");
}, 1000);
clearTimeout(timerId); // cancelled
console.log("Timer cancelled");Output:
Timer cancelledDebouncing is built entirely on this: "cancel the old timer, start a new one".
Debouncing
How It Works
Every time the event fires:
1. Cancel the timer that is waiting (if any)
2. Start a fresh timer for `delay` milliseconds
3. If no new event arrives before the timer ends → run the functionSo the function only runs after the user has been quiet for delay ms. Here's a timeline for a 300 ms debounce while someone types java:
time (ms): 0 100 200 300 600
keystroke: j ja jav java
timer: [--x [--x [--x [------------------] → search("java")
(each new key cancels the previous timer)Implementing debounce()
function debounce(fn, delay) {
let timerId; // remembered between calls (closure)
return function (...args) {
clearTimeout(timerId); // cancel the previous timer
timerId = setTimeout(() => {
fn.apply(this, args); // run with the latest arguments
}, delay);
};
}Let's understand each piece:
debounce()is a higher-order function: it takes a function and returns a new, "debounced" version of it.timerIdlives in the closure, so every call of the returned function sees and replaces the same timer....argscollects whatever arguments the event passes (for example, the search text).fn.apply(this, args)calls the original function with the samethisand arguments. The returned function is a regularfunctionso it receives the caller'sthis, and thesetTimeout()callback is an arrow function so it keeps thatthis(see thethisKeyword chapter).
Seeing It in Action
We can't type into Node.js, so let's simulate a user typing with timers. The user types java quickly, pauses, then types sc:
function debounce(fn, delay) {
let timerId; // remembered between calls (closure)
return function (...args) {
clearTimeout(timerId); // cancel the previous timer
timerId = setTimeout(() => {
fn.apply(this, args); // run with the latest arguments
}, delay);
};
}
let apiCalls = 0;
function search(query) {
apiCalls++;
console.log("Searching for: " + query);
}
const debouncedSearch = debounce(search, 300);
// Simulate a user typing "java", pausing, then typing "sc"
const keystrokes = [
{ time: 0, text: "j" },
{ time: 100, text: "ja" },
{ time: 200, text: "jav" },
{ time: 300, text: "java" },
// ... pause ...
{ time: 1000, text: "javas" },
{ time: 1100, text: "javasc" }
];
for (const key of keystrokes) {
setTimeout(() => {
console.log("typed: " + key.text);
debouncedSearch(key.text);
}, key.time);
}
setTimeout(() => {
console.log("Keystrokes: " + keystrokes.length + ", API calls: " + apiCalls);
}, 2000);Output:
typed: j
typed: ja
typed: jav
typed: java
Searching for: java
typed: javas
typed: javasc
Searching for: javasc
Keystrokes: 6, API calls: 2Six keystrokes, but only two searches, each with the complete text the user had typed when they paused. Without debouncing, we'd have sent six requests, four of which were for half-typed words nobody wanted.
Using It in the Browser
<input id="search" type="text" placeholder="Search courses">const input = document.querySelector("#search");
function searchCourses(query) {
console.log("Fetching results for: " + query);
}
const debouncedSearch = debounce(searchCourses, 300);
input.addEventListener("input", (event) => {
debouncedSearch(event.target.value);
});If the user types react quickly and stops, the console shows just one line:
Fetching results for: reactNotice that debounce(searchCourses, 300) is called once, outside the listener. That detail matters a lot; see Common Mistakes below.
Adding a cancel() Method
Sometimes a pending call should be dropped, for example if the user closes an editor before autosave fires. Since functions are objects, we can attach a method to the debounced function:
function debounce(fn, delay) {
let timerId;
function debounced(...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), delay);
}
debounced.cancel = function () {
clearTimeout(timerId);
};
return debounced;
}
const autosave = debounce(text => console.log("Autosaved: " + text), 500);
autosave("Draft 1");
autosave("Draft 2");
autosave.cancel(); // e.g. the user closed the editor
console.log("Cancelled, nothing will be saved");Output:
Cancelled, nothing will be savedLeading-Edge Debounce
The debounce above runs at the end of a burst (called trailing edge). Sometimes you want the first event to run immediately and the rest of the burst to be ignored (leading edge). A classic case is a "Pay" button that an impatient user double-clicks:
function debounceLeading(fn, delay) {
let timerId = null;
return function (...args) {
if (timerId === null) {
fn.apply(this, args); // first call of a burst runs immediately
}
clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = null; // quiet for `delay` ms: ready again
}, delay);
};
}
const pay = debounceLeading(amount => {
console.log("Payment of ₹" + amount + " started");
}, 300);
// Double/triple click quickly, then click again much later
setTimeout(() => pay(499), 0);
setTimeout(() => pay(499), 100);
setTimeout(() => pay(499), 200);
setTimeout(() => pay(499), 800);Output:
Payment of ₹499 started
Payment of ₹499 startedThe clicks at 0, 100 and 200 ms form one burst, so only the first one counts. The click at 800 ms comes after a 600 ms quiet gap, so it starts a new burst. (A real payment system must also block duplicates on the server; this just improves the user experience.)
Throttling
How It Works
Throttling doesn't wait for the events to stop. It lets the function run regularly while events keep coming, but never more often than once per interval:
1. When an event arrives, check: has `interval` ms passed since the last run?
2. YES → run the function and remember the time
3. NO → ignore this eventTimeline for a 250 ms throttle with a scroll event every 100 ms:
time (ms): 0 100 200 300 400 500 600 700 800 900 1000
event: ● ● ● ● ● ● ● ● ● ● ●
runs? RUN - - RUN - - RUN - - RUN -
(300 - 0 = 300 ≥ 250, so the event at 300 runs, and so on)Implementing throttle()
function throttle(fn, interval) {
let lastRun = 0; // time of the last real call (closure)
return function (...args) {
const now = Date.now();
if (now - lastRun >= interval) {
lastRun = now;
fn.apply(this, args);
}
// otherwise: ignore this call
};
}
const start = Date.now();
let handled = 0;
function onScroll(eventNumber) {
handled++;
const elapsed = Math.round((Date.now() - start) / 100) * 100;
console.log("Handled scroll event #" + eventNumber + " (~" + elapsed + " ms)");
}
const throttledScroll = throttle(onScroll, 250);
// Simulate 11 scroll events, one every 100 ms (0, 100, ..., 1000)
for (let i = 0; i <= 10; i++) {
setTimeout(() => throttledScroll(i), i * 100);
}
setTimeout(() => {
console.log("Events fired: 11, handler ran: " + handled + " times");
}, 1500);Output:
Handled scroll event #0 (~0 ms)
Handled scroll event #3 (~300 ms)
Handled scroll event #6 (~600 ms)
Handled scroll event #9 (~900 ms)
Events fired: 11, handler ran: 4 timesExactly what the timeline predicted. Date.now() (from the Date & Time chapter) gives the current time in milliseconds; we round the elapsed time only to make the output tidy.
A Timer-Based Throttle
The same idea can be written with a "cooling down" flag and setTimeout() instead of timestamps. Think of a game where a gun can fire at most once every 250 ms however fast you press the button:
function throttle(fn, interval) {
let waiting = false;
return function (...args) {
if (waiting) return; // still cooling down: ignore
fn.apply(this, args);
waiting = true;
setTimeout(() => {
waiting = false; // cool-down over
}, interval);
};
}
const fire = throttle(n => console.log("Bullet " + n + " fired"), 250);
for (let i = 0; i <= 10; i++) {
setTimeout(() => fire(i), i * 100);
}Output:
Bullet 0 fired
Bullet 3 fired
Bullet 6 fired
Bullet 9 firedBoth versions above are leading-edge throttles: they run on the first event of each interval. Their weakness is that the last event may be dropped (event #10 above never ran). For a scroll handler, that could mean the final scroll position is never processed. Production libraries such as Lodash's _.throttle() also do a trailing call by default: if events were ignored during an interval, the function runs once more at the end with the latest arguments.
Using It in the Browser
const throttledScroll = throttle(() => {
console.log("Scroll position: " + window.scrollY);
}, 200);
window.addEventListener("scroll", throttledScroll);While the user scrolls, the position is logged at most 5 times per second (1000 / 200), instead of on every single scroll event. window.scrollY is how many pixels the page has been scrolled vertically.
A Worked Example: Counting the Calls
This type of question appears in interviews and online tests, so let's calculate carefully.
Question: A user scrolls continuously for 3 seconds. The browser fires a scroll event every 20 ms, starting at t = 0. How many times does the handler run (a) with no control, (b) with a 200 ms leading-edge throttle, (c) with a 200 ms debounce?
(a) No control
Events at t = 0, 20, 40, ..., 3000
Number of events = 3000 / 20 + 1 = 151
Handler runs 151 times
(b) Throttle, interval = 200 ms (runs on the first event of each interval)
Runs at t = 0, 200, 400, ..., 3000
(every 200 ms there is an event exactly on time, since 200 is a multiple of 20)
Number of runs = 3000 / 200 + 1 = 16
(c) Debounce, delay = 200 ms
Each event comes 20 ms after the previous one, which is less than 200 ms,
so every event cancels the previous timer.
Only the last event (t = 3000) survives.
Handler runs 1 time, at t = 3000 + 200 = 3200 msGeneral rules for a continuous burst of events lasting T ms:
Throttle (leading edge, events frequent enough): about
floor(T / interval) + 1runs, spread evenly through the burst.Debounce: 1 run,
delayms after the last event, as long as the gap between events is less thandelay.If the debounce delay is smaller than the gap between events (say a 10 ms delay with events every 20 ms), every timer finishes before the next event arrives, so all 151 events run, and debouncing does nothing.
Debounce vs Throttle
Aspect | Debounce | Throttle |
|---|---|---|
Rule | Run after events stop for | Run at most once per |
During a long continuous burst | Doesn't run at all until the burst ends | Runs regularly throughout |
Number of runs for one burst | 1 | About |
Which event's data is used | The last one (trailing) or the first one (leading) | The first event of each interval (plus the last, with trailing) |
Built with |
| A timestamp or a cooling-down flag |
Typical uses | Search box suggestions, form validation while typing, autosave, window resize "finished" | Scroll position, infinite scroll, mouse move / drag, progress tracking, game controls, rate-limiting API calls |
A quick way to choose: "Do I only care about the final value?" Use debounce. "Do I need regular updates while it's happening?" Use throttle.
For example, a reading-progress bar at the top of a blog must move while you scroll, so it needs throttling. If you debounced it, the bar would freeze during scrolling and jump only when you stop.
For purely visual updates (animations, moving an element with the mouse), browsers also offer
requestAnimationFrame(), which runs your code right before the next screen repaint, usually about 60 times per second. It's a natural "throttle to the screen's refresh rate".
Complexity
Each call to a debounced or throttled function does a constant amount of work (compare a timestamp, or clear and set one timer), so the overhead is O(1) time and O(1) memory per call. The benefit is in how many times the expensive function runs: from one per event (for example 151) down to one per burst (debounce) or one per interval (throttle).
Common Mistakes
1. Creating the Debounced Function Inside the Handler
function debounce(fn, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
function search(query) {
console.log("Searching for: " + query);
}
// WRONG: a brand-new debounced function (with its own timerId) on every event
function onInputWrong(text) {
debounce(search, 300)(text);
}
["r", "re", "rea", "reac"].forEach((text, i) => {
setTimeout(() => onInputWrong(text), i * 50);
});Output:
Searching for: r
Searching for: re
Searching for: rea
Searching for: reacEach call to debounce() creates a new closure with a new, empty timerId, so no call ever cancels another. Create the debounced function once and reuse it, as in the browser example earlier.
2. Losing this or the Arguments
If your wrapper calls fn() instead of fn.apply(this, args), the original function receives no arguments and the wrong this. With apply, methods keep working:
function debounce(fn, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
const editor = {
name: "Notes",
save: debounce(function (text) {
console.log(this.name + " saved: " + text);
}, 200)
};
editor.save("Hello");
editor.save("Hello World");Output:
Notes saved: Hello WorldAlso, the returned wrapper must be a regular function, not an arrow function, or it can't receive this from editor.save(...).
3. Other Mistakes
Choosing the wrong one. Debouncing a scroll-progress bar makes it freeze during scrolling; throttling a search box sends requests for half-typed words.
Picking a bad delay. Too short and you barely reduce the number of calls; too long and the app feels laggy. Around 200 to 500 ms is common for typing, and 100 to 250 ms for scroll.
Forgetting to remove listeners or cancel pending calls when a component or page section is removed, so a delayed call runs on something that no longer exists.
Thinking debounce makes slow code faster. It only reduces how often the code runs. The function itself is just as slow.
Interview Tips
A good short answer to "What is the difference between debouncing and throttling?":
"Both limit how often a function runs in response to frequent events. Debouncing delays the call until the events have stopped for a given time, so a burst produces one call, which is ideal for search boxes and autosave. Throttling guarantees the function runs at most once per interval while events continue, which suits scroll, resize and mousemove handlers. Debounce is implemented with
setTimeoutandclearTimeoutin a closure; throttle with a timestamp or a flag."
Be ready to:
Write
debounce(fn, delay)from memory, including...argsandfn.apply(this, args), and explain why the closure is needed.Write
throttle(fn, interval), in either the timestamp or flag style.Explain leading vs trailing execution, and mention that Lodash provides
_.debounce()(withleading,trailingandmaxWaitoptions) and_.throttle().Solve counting questions like the worked example above.
Pick the right technique for a given scenario: search box, infinite scroll, window resize, "Submit" double-click, live cursor position.
Practice: (1) Add a flush() method to debounce() that immediately runs the pending call, if any. (2) A button is clicked at t = 0, 150, 300, 450 and 1200 ms. How many times does the handler run with a 200 ms trailing debounce, and at what times? (Answer: 2 times, at 650 ms and 1400 ms.)
Conclusion
Debouncing and throttling control how often a function runs when events fire rapidly.
Debounce: wait until events stop for
delayms, then run once. Perfect for search boxes, validation and autosave.Throttle: run at most once per
intervalms while events continue. Perfect for scroll, resize, mousemove and game controls.Both are small higher-order functions that use a closure to remember a timer or a timestamp.
Use
clearTimeout()to cancel the pending timer in debounce.Create the debounced/throttled function once, and forward
thisand the arguments withfn.apply(this, args).
You'll use debouncing again in the next chapter, where validating a form while the user types is a perfect fit for it.