Lesson 78 of 296
debounce and throttle
On this page
The task
"Implement debounce(fn, delay)." Often followed by: "Now implement throttle(fn, interval). What is the difference?"
What they are for
Some events fire very often: typing, scrolling, resizing the window, moving the mouse. Running expensive code (an API request, a layout calculation) on every single event wastes resources and makes the page slow.
| Debounce | Throttle | |
|---|---|---|
| Rule | Wait until the events stop for a set time, then run once | Run at most once per set time while the events continue |
| Example | Search box: only search when the user pauses typing for 300 ms | Scroll handler: update a progress bar at most every 100 ms while scrolling |
| If events never stop | It never runs | It runs regularly |
Plain way to remember:
- Debounce: "wait until they stop, then do it once".
- Throttle: "do it, then not again until the time is up".
What the interviewer is checking
- Closures, to keep the timer between calls (Lesson 53).
setTimeoutandclearTimeout.- Keeping
thisand the arguments. - Edge cases: leading or trailing calls, and cancelling.
Questions to ask first
- "Should it run at the end of the wait (trailing), at the start (leading), or both?"
- "Do you want a
cancelmethod?"
debounce, step by step
- Keep a timer ID in a closure.
- Every call: cancel the previous timer, then start a new one.
- When a timer finally completes (no new call arrived in time), run the function with the latest arguments.
function debounce(fn, delay) {
let timerId;
function debounced(...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
debounced.cancel = () => clearTimeout(timerId);
return debounced;
}debouncedis a normal function so it receives the caller'sthis. The arrow function insidesetTimeoutkeeps thatthis.clearTimeout(undefined)is safe on the first call.
Usage:
const search = debounce((text) => {
fetch(`/api/search?q=${encodeURIComponent(text)}`);
}, 300);
input.addEventListener("input", (e) => search(e.target.value));Test it
const calls = [];
const d = debounce((x) => calls.push(x), 50);
d(1); d(2); d(3);
after 100 ms: calls is [3]throttle, step by step
This version runs immediately on the first call (leading), and also makes sure the last call in a burst is not lost (trailing):
function throttle(fn, interval) {
let lastRun = 0;
let timerId = null;
let lastArgs;
let lastThis;
return function throttled(...args) {
const now = Date.now();
const remaining = interval - (now - lastRun);
lastArgs = args;
lastThis = this;
if (remaining <= 0) {
clearTimeout(timerId);
timerId = null;
lastRun = now;
fn.apply(lastThis, lastArgs);
} else if (!timerId) {
timerId = setTimeout(() => {
lastRun = Date.now();
timerId = null;
fn.apply(lastThis, lastArgs);
}, remaining);
}
};
}- If enough time has passed since the last run, run now.
- Otherwise, if no trailing run is scheduled yet, schedule one for when the interval ends, using the latest arguments.
Simpler version (leading only, the most common first answer in interviews):
function throttleSimple(fn, interval) {
let lastRun = 0;
return function (...args) {
const now = Date.now();
if (now - lastRun >= interval) {
lastRun = now;
fn.apply(this, args);
}
};
}Mention that it drops the last call of a burst, then offer the full version.
Test it
const t = [];
const th = throttle((x) => t.push(x), 100);
th(1); th(2); th(3);
after 150 ms: t is [1, 3] (1 ran now; 3 was the trailing call)Follow-up questions
- "Add a leading option to debounce." Run on the first call if no timer is active, then ignore calls until the wait ends.
- "Why use these in React?" Search inputs and resize handlers. In React, create the debounced function once (for example with
useMemooruseRef), otherwise each render makes a new one with a new timer (Part 12). - "What about
requestAnimationFrame?" For visual updates during scroll,requestAnimationFramelimits work to once per screen refresh; it is a natural throttle for animations.
Common mistakes
- Creating the timer variable inside the returned function, so every call has its own timer and nothing is cancelled.
- Losing
thisor the arguments. - Mixing up which one waits for silence (debounce) and which one runs regularly (throttle).
How to say it in an interview
"Debounce delays running until calls have stopped for the given time, so I keep a timer in a closure, clear it on every call and set a new one; it suits search-as-you-type. Throttle runs at most once per interval while calls continue; I store the last run time, run immediately if the interval has passed, and otherwise schedule one trailing call with the latest arguments, which suits scroll and resize. Both preserve this and the arguments, and debounce can expose a cancel method."
Key words
| Word | Meaning |
|---|---|
| Debounce | Run once after the calls stop for a set time |
| Throttle | Run at most once per set time |
| Leading call | Running at the start of a burst of calls |
| Trailing call | Running at the end of a burst of calls |
| Timer ID | The value returned by setTimeout, used to cancel it |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.