Code snippets
JavaScript Debounce and Throttle Explained With Code
Debounce waits until events stop arriving and then runs your function once, while throttle runs it at a steady maximum rate while events keep arriving. Use debounce for search-as-you-type and resize-end work, and throttle for scroll and pointer tracking.
By CodingMarble · Published · 6 min read

The problem: events fire far more often than you need
Some browser events arrive in bursts. A scroll event can fire many times during a single flick of the trackpad, a resize event fires continuously while someone drags a window edge, and an input event fires on every keystroke. If each of those events triggers real work, such as a network request, a layout measurement or a filter over a long list, the page spends its time reacting to intermediate states nobody cares about.
Take search-as-you-type. A user typing the word 'keyboard' produces eight input events in a second or two. Sending eight requests is wasteful, and worse, responses can come back out of order, so the results for 'keyb' may overwrite the results for 'keyboard'. What you want is one request after the user pauses. That is debouncing.
Now take a sticky header that changes style once the page has scrolled past a threshold. Waiting until the user stops scrolling would feel broken, because the header should react during the scroll. What you want here is a check at a sensible, bounded rate while scrolling continues. That is throttling.
Both techniques wrap a function and return a new function that you pass to addEventListener. They differ in when the wrapped function is allowed to run, and picking the wrong one is the most common mistake.
A debounce with leading and trailing options
A basic debounce clears a timer on every call and starts a new one. When the timer finally completes without being reset, the function runs. The version below adds two options. With trailing set to true, the default, the function runs after the quiet period using the most recent arguments. With leading set to true, it also runs immediately on the first call of a burst, which suits a button that should react at once but ignore accidental double clicks.
export function debounce(fn, wait = 300, { leading = false, trailing = true } = {}) {
let timer = null;
let lastArgs, lastThis, result;
function invoke() {
const [args, ctx] = [lastArgs, lastThis];
lastArgs = lastThis = undefined;
result = fn.apply(ctx, args);
return result;
}
function debounced(...args) {
lastArgs = args;
lastThis = this;
const startNow = leading && timer === null;
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (trailing && lastArgs) invoke();
lastArgs = lastThis = undefined;
}, wait);
if (startNow) invoke();
return result;
}
debounced.cancel = () => {
clearTimeout(timer);
timer = null;
lastArgs = lastThis = undefined;
};
debounced.flush = () => {
if (timer === null || !lastArgs) return result;
clearTimeout(timer);
timer = null;
return invoke();
};
return debounced;
}Walk through the details. The timer variable doubles as a state flag: null means no burst is in progress. Each call stores its arguments and this value so the delayed run uses the latest ones, not the first. The startNow check reads the timer before it is reset, so only the first call of a burst counts as leading. When the leading call has already consumed the arguments, lastArgs is undefined by the time the timer completes, so a single call with both options does not run twice. Two calls in the same burst do run twice: once at the start, once at the end.
The cancel method matters more than people expect. Without it, a pending call can fire after a component has been removed from the page. The flush method runs the pending call immediately, which is useful when a user presses Enter in a search box and you do not want to wait for the quiet period.
A throttle that keeps the latest call
A throttle ensures the function runs at most once per interval. The naive version drops every call made inside the interval, which means the final scroll position can be lost if the last event lands in a dead zone. The version below fixes that by scheduling one trailing run for the most recent arguments.
export function throttle(fn, wait = 200) {
let last = 0;
let timer = null;
let lastArgs;
let lastThis;
function run(now) {
last = now;
timer = null;
const args = lastArgs;
const ctx = lastThis;
lastArgs = lastThis = undefined;
fn.apply(ctx, args);
}
function throttled(...args) {
lastArgs = args;
lastThis = this;
const now = Date.now();
const remaining = wait - (now - last);
if (remaining <= 0) {
if (timer) clearTimeout(timer);
run(now);
} else if (!timer) {
timer = setTimeout(() => run(Date.now()), remaining);
}
}
throttled.cancel = () => {
clearTimeout(timer);
timer = null;
lastArgs = lastThis = undefined;
};
return throttled;
}On the first call, last is zero, so remaining is negative and the function runs immediately. Calls inside the next interval only update the stored arguments and, if no timer exists, schedule one for the time that remains. When that timer fires, it runs with whatever arguments arrived last. If you call the throttled function every ten milliseconds for a third of a second with a one hundred millisecond interval, it runs roughly every hundred milliseconds, plus a final run once the events stop.
How they differ, and which one to choose
The cleanest way to remember the difference is to ask what happens during a continuous stream of events. A debounced function does nothing until the stream pauses. A throttled function keeps running at a capped rate for as long as the stream lasts.
- Search-as-you-type, autosave, form validation on typing: debounce. You care about the settled value, not the intermediate ones.
- Window resize that recalculates a layout: debounce if the recalculation is expensive and only the final size matters, throttle if the layout should follow the drag.
- Scroll-position checks, parallax, infinite-scroll triggers, pointer tracking: throttle, because the user expects feedback during the gesture.
- Double-click protection on a submit button: debounce with leading true and trailing false, so the first click goes through and the rest are ignored.
A useful rule of thumb for the wait value is to match human perception. Typing pauses are fine in the range of a few hundred milliseconds. Scroll feedback usually feels responsive at intervals near a frame or a few frames. Treat these as starting points and tune them on a real mid-range phone, not only on a fast desktop.
Using them in a search box and a scroll handler
Here is the pairing in plain JavaScript. The search handler is debounced and uses an AbortController so that an older request cannot overwrite a newer one, which solves the out-of-order problem described earlier. The scroll handler is throttled and only toggles a class.
import { debounce } from "./debounce.js";
import { throttle } from "./throttle.js";
const input = document.querySelector("#search");
const list = document.querySelector("#results");
let controller = null;
async function search(term) {
if (controller) controller.abort();
if (term.trim().length < 2) {
list.replaceChildren();
return;
}
controller = new AbortController();
try {
const res = await fetch("/api/search?q=" + encodeURIComponent(term), {
signal: controller.signal,
});
const items = await res.json();
list.replaceChildren(
...items.map((i) => Object.assign(document.createElement("li"), { textContent: i.title }))
);
} catch (err) {
if (err.name !== "AbortError") console.error(err);
}
}
const debouncedSearch = debounce(search, 300);
input.addEventListener("input", (e) => debouncedSearch(e.target.value));
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") debouncedSearch.flush();
});
const header = document.querySelector("header");
const onScroll = throttle(() => {
header.classList.toggle("is-compact", window.scrollY > 80);
}, 100);
window.addEventListener("scroll", onScroll, { passive: true });Two details are worth noting. The scroll listener is marked passive, which tells the browser the handler will not call preventDefault, so scrolling is never blocked waiting for your code. And the search function ignores terms shorter than two characters, because a request for a single letter rarely returns anything useful. The endpoint path is a placeholder; point it at your own API.
Cancelling on unmount in React
In React, the classic mistake is creating a new debounced function on every render, which resets the timer each time the component updates and silently defeats the debounce. The wrapped function must be stable across renders, and the pending call must be cancelled when the component unmounts. A small hook handles both. It keeps the latest callback in a ref so the debounced wrapper never needs to be recreated.
import { useEffect, useMemo, useRef, useState } from "react";
import { debounce } from "./debounce";
export function useDebouncedCallback<A extends unknown[]>(
callback: (...args: A) => void,
wait: number
) {
const ref = useRef(callback);
useEffect(() => {
ref.current = callback;
});
const debounced = useMemo(
() => debounce((...args: A) => ref.current(...args), wait),
[wait]
);
useEffect(() => () => debounced.cancel(), [debounced]);
return debounced;
}
export function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
const [value, setValue] = useState("");
const run = useDebouncedCallback(onSearch, 300);
return (
<input
value={value}
onChange={(e) => {
setValue(e.target.value);
run(e.target.value);
}}
/>
);
}The input value updates immediately through state, so typing never feels laggy; only the expensive callback is delayed. The cleanup effect returns a function that cancels any pending call, which prevents a request from firing against a component that no longer exists. If your project already uses a utility library that ships a debounce function, the same pattern applies: keep the wrapper stable and cancel it on cleanup, and check that library's documentation for the exact method names.
requestAnimationFrame and testing with fake timers
For visual updates that follow scroll or pointer movement, requestAnimationFrame is often a better throttle than a fixed number of milliseconds. It runs at most once per rendered frame and pauses in background tabs. The pattern is to record the latest value in the event handler and apply it inside a single scheduled frame.
let ticking = false;
let latestY = 0;
window.addEventListener(
"scroll",
() => {
latestY = window.scrollY;
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
document.documentElement.style.setProperty("--scroll", String(latestY));
ticking = false;
});
},
{ passive: true }
);Timing code is easy to get subtly wrong, so test it without real waiting. Test runners such as Vitest and Jest provide fake timers that let you move the clock forward on demand. The test below checks that three rapid calls produce one run with the last argument, and that cancel prevents a pending run. Confirm the exact API names against your runner's documentation, because they differ slightly between tools and versions.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { debounce } from "./debounce.js";
describe("debounce", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it("runs once with the last arguments", () => {
const fn = vi.fn();
const d = debounce(fn, 100);
d(1);
d(2);
d(3);
vi.advanceTimersByTime(99);
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith(3);
});
it("does nothing after cancel", () => {
const fn = vi.fn();
const d = debounce(fn, 100);
d("x");
d.cancel();
vi.advanceTimersByTime(500);
expect(fn).not.toHaveBeenCalled();
});
});Common mistakes to look for when reviewing code: creating the debounced function inside an event handler so each event gets its own timer, forgetting to cancel on unmount, using debounce where throttle was needed so the interface appears frozen during a scroll, and choosing a wait so long that the interface feels unresponsive. Test the last one by actually using the feature on a phone.
Keep reading
- Code snippetsBuild an EMI Calculator in JavaScript (With Schedule)An EMI calculator applies one formula, EMI = P * r * (1+r)^n / ((1+r)^n - 1), where r is the annual rate divided by 12 and by 100 and n is the number of months. This tutorial turns it into a validated function, an amortisation schedule and a working HTML form, with every printed number checked by running the code.
- Interview questions and cheat sheetsReact Interview Questions and AnswersThis page covers sixteen React interview questions in three groups: fundamentals, hooks and performance, and advanced topics. Each answer explains the reasoning and, where it helps, shows a short example.
- Interview questions and cheat sheetsJavaScript Interview Questions and AnswersThis page gives you eighteen JavaScript interview questions, grouped from fundamentals to trick questions, each with a precise answer you can say aloud in under a minute. Code examples are short enough to rewrite on a whiteboard.
- Web developmentHow to Speed Up a Next.js WebsiteMost slow Next.js sites are slow for ordinary reasons: oversized images, late-loading fonts, too much client-side JavaScript and uncached data. Fix those four in order, and measure with both Lighthouse and real-user data so you know the change helped.
Need this built properly for your business?
CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.