Throttle
Throttling runs a function at most once per interval, which is what you want when the intermediate values matter.
Debounce waits for quiet; throttle guarantees a steady rate. Two implementations exist, one using a timestamp and one using a timer, and they differ in whether the final call is honoured. Choosing between throttle and debounce is a question about whether you need updates during the activity.
EXERCISE
1Steady Rate, Not Silence
The difference from debounce is what happens during a long burst of activity.
Debounce waits until the activity stops. If the activity never stops, the function never runs. For a scroll position or a mouse coordinate that is exactly wrong, because the whole point is to update while it is happening.
Side by side:
// Events at 0, 50, 100, 150, 200, 250, 300ms
// Debounce, 100ms: runs once, at 400ms
// Throttle, 100ms: runs at 0, 100, 200, 300ms
Debounce gives you the last value. Throttle gives you a value at a steady rate.
The timestamp implementation:
function throttle(fn, interval) {
let lastRun = 0;
return function (...args) {
const now = Date.now();
if (now - lastRun >= interval) {
lastRun = now;
fn.apply(this, args);
}
};
}
Eight lines and no timer at all. Each call checks the clock and either runs or is dropped.
It has one flaw, and it is the flaw the interview is usually testing for:
// Events at 0, 50, 90ms then nothing. Interval 100ms.
// Runs at 0. The calls at 50 and 90 are dropped.
// The final position, at 90ms, is never used.
The last event in a burst is lost, which for a scroll handler means the final resting position is never rendered.
The timer implementation, which keeps the trailing call:
function throttle(fn, interval) {
let timerId = null;
let lastArgs = null;
return function (...args) {
lastArgs = args;
if (timerId === null) {
fn.apply(this, args);
timerId = setTimeout(() => {
timerId = null;
if (lastArgs !== args) {
fn.apply(this, lastArgs);
}
}, interval);
}
};
}
It runs immediately, then blocks for the interval, then runs once more with the most recent arguments if any arrived while it was blocked. The lastArgs !== args check avoids running twice with the same values when only one call arrived.
Where each one belongs:
// Throttle: scroll position, mouse tracking, a progress bar,
// rate-limiting an API, anything where intermediate
// values are meaningful.
//
// Debounce: search input, autosave, resize completion, anything
// where only the final value matters.
The question that picks correctly every time:
// "If this activity continues for ten seconds, should anything
// happen during those ten seconds?"
//
// Yes -> throttle
// No -> debounce
Pro Tip: For anything that updates the screen,
requestAnimationFrameis usually a better throttle than a time interval. It runs once per frame, synchronised with the browser's repaint, so you never compute a position that gets thrown away before it is drawn. Unit 4 covered it; this is where it earns its place.
EXERCISE
2Rate Limiting Beyond the Browser
The same idea appears on the server, where the constraint is a quota rather than a frame rate.
Throttling in a browser protects the frame budget. On a or against a third-party , it protects a limit somebody else enforces, and exceeding it costs money or gets you blocked.
A queue that releases at a fixed rate:
function createRateLimiter(callsPerSecond) {
const interval = 1000 / callsPerSecond;
let queue = [];
let running = false;
async function drain() {
running = true;
while (queue.length > 0) {
const { fn, resolve, reject } = queue.shift();
try {
resolve(await fn());
} catch (err) {
reject(err);
}
await new Promise((r) => setTimeout(r, interval));
}
running = false;
}
return function limit(fn) {
return new Promise((resolve, reject) => {
queue.push({ fn, resolve, reject });
if (!running) {
drain();
}
});
};
}
const limit = createRateLimiter(5); // five per second
const results = await Promise.all(
urls.map((url) => limit(() => fetch(url))),
);
Every call is queued and released at the allowed rate, and each caller still gets a promise for its own result. Nothing is dropped, which is the important difference from a browser throttle: here, discarding a call would lose work rather than skip a redundant repaint.
Which is the distinction worth holding:
// Browser throttle: DROPS calls. The skipped ones were redundant.
// Rate limiter: DELAYS calls. Every one still has to happen.
Using the wrong one is a real bug. A dropping throttle in front of a payment API silently loses requests.
The queue is what makes this a limiter rather than a throttle. A browser throttle can discard a call because the next scroll event carries newer information and the skipped one was already obsolete. A request to an API is not obsolete; somebody is waiting for its result. So the work is delayed rather than dropped, and every caller still gets an answer.
Backing off when the server tells you to:
async function requestWithBackoff(url, attempt = 0) {
const response = await fetch(url);
if (response.status === 429) {
const retryAfter = Number(response.headers.get("Retry-After") ?? 1);
const wait = Math.max(retryAfter * 1000, 2 ** attempt * 1000);
await new Promise((r) => setTimeout(r, wait));
return requestWithBackoff(url, attempt + 1);
}
return response;
}
A 429 is the server saying you are going too fast, and Retry-After is it telling you how long to wait. Honouring that header is both correct and polite, and ignoring it is how an integration gets its key revoked.
Combine the two and you have the shape most production API clients use: a limiter for the rate you expect, and backoff for when you were wrong.
EXERCISE
3Reading the Standard Implementations
Lodash and friends add several options to both functions, and knowing what they mean makes the documentation readable.
Almost every project already has a debounce and a throttle from a library. Knowing what the options do is more useful than rewriting them.
The options you will meet:
_.debounce(fn, 300, {
leading: false, // run at the start of a burst
trailing: true, // run at the end of a burst
maxWait: 1000, // run at least this often during a long burst
});
_.throttle(fn, 300, {
leading: true,
trailing: true,
});
And the fact that ties the two together:
// throttle(fn, wait) is debounce(fn, wait, { maxWait: wait })
They are the same function with different defaults. A debounce that is forced to run at least every maxWait milliseconds during continuous activity is a throttle. That is worth knowing because it explains why one library function implements both, and because it reframes the choice as one dial rather than two tools.
The four combinations:
// leading, no trailing fires immediately, ignores the rest
// -> a submit button
// no leading, trailing waits for quiet, then fires (the default)
// -> a search box
// leading and trailing fires immediately and again at the end
// -> a scroll handler wanting both edges
// neither never fires. A configuration mistake.
That last row is a real bug people ship, because { leading: false, trailing: false } is accepted without complaint and produces a function that does nothing.
What the library versions add that a hand-rolled one usually does not:
const debounced = _.debounce(save, 300);
debounced.cancel(); // drop the pending call
debounced.flush(); // run it right now instead of waiting
debounced.pending(); // is there one waiting?
flush is the one worth knowing about. Saving a draft on a debounce and then flushing when the user navigates away means they never lose the last few seconds of typing.
And when to write your own anyway:
// A dependency for eight lines is a real cost in a small project.
// The hand-rolled version is fine when you need the default
// behaviour and a cancel. Reach for the library when you find
// yourself wanting maxWait or flush, because those are where
// the edge cases live.
Pro Tip: Whichever you use, hold the debounced function somewhere stable and call
cancelwhen the thing that owns it goes away. Every remaining problem with these two functions in real code is either creating them in the wrong place or failing to cancel them, and neither is about the implementation.
