If you have ever typed into a search box and watched the page fire a network request on every single keystroke, you have seen the problem that debounce and throttle solve. Events like typing, scrolling, resizing the window, and moving the mouse can fire dozens or even hundreds of times per second. Running an expensive function on every event wastes CPU, floods your server with requests, and makes the interface feel sluggish. Debounce and throttle are two small utility patterns that control how often a function is allowed to run. They are not built into JavaScript, but both can be written in under fifteen lines, and once you understand them you will reach for them in almost every project.
Although debounce and throttle javascript techniques sound similar, they behave differently and suit different jobs. Debounce waits until the event stops happening for a set period before running the function once. Throttle guarantees the function runs at most once in a set interval, even if the event keeps firing. Choosing the wrong one leads to subtle bugs, such as a search box that feels too slow or a scroll handler that still runs too often. This guide explains both patterns with complete, copy-ready code, walks through what each line does, and shows real examples you can adapt for search inputs, infinite scroll, window resizing, and button clicks.
What Is Debounce and When Should You Use It?
Debounce groups a rapid burst of events into a single call. Imagine a user typing the word “javascript” into a search field. Without debounce, the input event fires ten times, once per letter. With debounce set to 300 milliseconds, each keystroke resets a timer. Only when the user pauses for a full 300 milliseconds does the search function finally run, and it runs just once with the complete word. This is ideal whenever you only care about the final value after the user has finished an action.
Common debounce use cases include live search suggestions, form validation that checks a value after typing stops, filtering a list as the user types, and saving a draft a short moment after editing stops. If you are fetching results for that search, pair this pattern with the examples in our Fetch API examples guide so you send one request instead of ten. Debounce is less suitable when you need regular feedback during a continuous action, such as updating a progress indicator while scrolling. In those cases throttle is the better fit.
A Simple Debounce Implementation
function debounce(fn, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
const handleSearch = debounce(function (event) {
console.log("Searching for:", event.target.value);
}, 300);
document.querySelector("#search").addEventListener("input", handleSearch);
The code above creates a reusable debounce helper. The outer function takes two arguments: fn, the function you want to control, and delay, the waiting period in milliseconds. Inside, timerId stores the ID of the pending timer, and because it lives in the closure it is remembered between calls. The helper returns a new function, which is the one you actually attach to the event. Every time that returned function runs, clearTimeout(timerId) cancels any previously scheduled call. Then setTimeout schedules a fresh call after the delay. The spread syntax ...args collects whatever arguments the original event passed, and fn.apply(this, args) calls your function with the correct this value and those arguments. If events keep arriving faster than the delay, the timer keeps resetting and your function never runs until there is a quiet pause.
To use it, we wrap a simple logging function with a 300 millisecond delay and attach the wrapped version to the input event of a search field. Try typing quickly and slowly in a test page and watch the console. Fast typing produces a single log line, while typing with pauses longer than 300 milliseconds produces one log line per pause. That small difference is exactly the behaviour users expect from a polished search box.
What Is Throttle and When Should You Use It?
Throttle limits how often a function can run over time. Instead of waiting for a pause, throttle lets the function run immediately, then ignores further calls until a set interval has passed. If you throttle a scroll handler to 200 milliseconds, it will run at most five times per second no matter how frantically the user scrolls. The page still responds continuously, but at a controlled, predictable rate.
Throttle fits situations where you need steady updates during an ongoing action: tracking scroll position to show a reading progress bar, handling window resize while a layout recalculates, responding to mousemove for a drawing canvas, or preventing a submit button from being double-clicked. For tasks like filtering data while scrolling through large lists, throttle also works well alongside the patterns covered in our JavaScript array methods cheat sheet, where fast methods like map and filter keep each throttled call cheap.
A Simple Throttle Implementation
function throttle(fn, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn.apply(this, args);
}
};
}
const handleScroll = throttle(function () {
console.log("Scroll position:", window.scrollY);
}, 200);
window.addEventListener("scroll", handleScroll);
This throttle helper also returns a wrapped function, but its logic is different. The variable lastCall records the timestamp of the most recent time the function actually ran, starting at zero. On each event, the wrapper reads the current time with Date.now(). It subtracts lastCall from the current time and checks whether at least limit milliseconds have passed. If they have, it updates lastCall and runs your function with fn.apply(this, args), preserving context and arguments just like the debounce version. If not enough time has passed, the wrapper simply does nothing and the event is ignored. The result is a steady maximum rate with no trailing call after the last event, which is fine for scroll and resize work.
In the example, the scroll handler logs the vertical scroll position at most once every 200 milliseconds. Without throttle, a single scroll gesture can fire the listener more than a hundred times. With throttle, you get a handful of useful updates, enough to animate a progress bar smoothly without wasting cycles.
Debounce vs Throttle: A Side-by-Side Comparison
It helps to picture both patterns handling the same burst of ten events spread over one second. Debounce with a 300 millisecond delay would run the function once, at the very end, after the burst settles. Throttle with a 300 millisecond limit would run it roughly three or four times, spaced evenly across the second. Debounce answers the question “what is the final state?” while throttle answers “what is happening right now, sampled at a reasonable rate?”
Ask yourself two questions when choosing. First, does intermediate output matter? If only the last value matters, such as a completed search term, choose debounce. If the user needs visible feedback throughout, such as a sticky header changing as they scroll, choose throttle. Second, how expensive is the function? Very expensive work, like a network request, usually belongs behind debounce so it runs as rarely as possible. Moderately cheap work, like toggling a CSS class, can be throttled and still feel responsive. Many production codebases use both on the same page for different events, and libraries like Lodash provide battle-tested versions with extra options for leading and trailing calls.
Practical Example: Debounced Search With Fetch
Here is a complete pattern that combines debounce with a real request. It waits for the user to stop typing, then loads matching results. It also handles the case where the input is cleared, so no useless request is sent for an empty string.
const resultsBox = document.querySelector("#results");
async function searchProducts(query) {
if (!query.trim()) {
resultsBox.innerHTML = "";
return;
}
const response = await fetch(
"https://dummyjson.com/products/search?q=" + encodeURIComponent(query)
);
const data = await response.json();
resultsBox.innerHTML = data.products
.map((item) => `<li>${item.title}</li>`)
.join("");
}
const debouncedSearch = debounce(searchProducts, 400);
document.querySelector("#search").addEventListener("input", (event) => {
debouncedSearch(event.target.value);
});
In this snippet, searchProducts is an async function that receives the query string directly instead of the whole event, which makes it easier to test. It returns early if the trimmed query is empty and clears the results area. Otherwise it builds a URL with encodeURIComponent so spaces and special characters are sent safely, awaits the fetch response, converts it to JSON, and renders product titles as list items using map and join. The debounced wrapper waits 400 milliseconds after the last keystroke before calling it. Notice how the input listener passes only event.target.value, keeping the search function decoupled from the DOM. If you save the last query so returning users see it again, the techniques in our localStorage guide fit naturally here.
Practical Example: Throttled Resize Handler
Window resize is another event that fires in rapid bursts as the user drags the corner of the browser. Recalculating a layout on every pixel of movement is wasteful. Throttling the handler keeps the layout correct while cutting the work dramatically.
function updateLayoutLabel() {
const width = window.innerWidth;
let label = "Desktop";
if (width < 600) {
label = "Mobile";
} else if (width < 1024) {
label = "Tablet";
}
document.querySelector("#layout-label").textContent = label;
}
const throttledResize = throttle(updateLayoutLabel, 250);
window.addEventListener("resize", throttledResize);
updateLayoutLabel();
The function updateLayoutLabel reads window.innerWidth and picks a label using simple breakpoints, then writes that label into the page. The throttled version runs at most once every 250 milliseconds during a drag, which is frequent enough that the label feels live but cheap enough to avoid layout thrashing. We also call the plain function once on load so the label is correct before any resize happens. Responsive breakpoint logic like this pairs well with the CSS side of the same problem, which we cover in our CSS responsive media queries notes. For date-driven UI, such as “last updated” labels refreshed on resize or scroll, you may also want our notes on formatting values before display.
Common Mistakes to Avoid
The most frequent mistake is creating the debounced function inside the event listener or inside a render cycle. If you write input.addEventListener("input", debounce(handler, 300)) in code that runs repeatedly, you create a brand-new timer on every run and nothing ever gets cancelled. Always create the wrapped function once and reuse it. A second mistake is choosing a delay that is too long. A search delay above 500 milliseconds feels broken to users, while delays under 100 milliseconds barely reduce the call count. For most typing cases, 250 to 400 milliseconds is a good range to test.
A third mistake is forgetting about this. If your handler is an object method that relies on this, an arrow function or a careless wrapper can break it. The implementations above use a regular function plus apply specifically to preserve context. Finally, remember to clean up in component-based frameworks: cancel pending timers when a component unmounts, otherwise a debounced callback can fire after the element is gone and throw an error when it touches missing DOM nodes.
Advanced Options: Leading and Trailing Calls
The basic versions above cover most needs, but two refinements are worth knowing. A leading-edge call runs the function immediately on the first event, then starts the waiting period. This is useful for buttons, where the user expects instant feedback but must not trigger the action twice. A trailing-edge call, which is what our debounce does, runs after the quiet period. Some utilities let you enable both. If you need these options regularly, using the well-tested Lodash _.debounce and _.throttle functions is reasonable, but writing the basic versions yourself first ensures you understand what the library is doing when something behaves unexpectedly.
function throttleWithTrailing(fn, limit) {
let lastCall = 0;
let timerId = null;
return function (...args) {
const now = Date.now();
const remaining = limit - (now - lastCall);
if (remaining <= 0) {
lastCall = now;
fn.apply(this, args);
} else if (!timerId) {
timerId = setTimeout(() => {
lastCall = Date.now();
timerId = null;
fn.apply(this, args);
}, remaining);
}
};
}
This enhanced throttle adds a trailing call. It calculates how much time remains in the current window. If the window has expired, it runs immediately as before. If not, and no trailing timer is already set, it schedules one final call for when the window ends, using the latest arguments. That guarantees the last scroll or resize position is never missed, which matters when the final position determines what the user sees. The extra complexity is only worth it when that final update matters; for simple logging or class toggling, the basic version is cleaner.
Conclusion
Debounce and throttle are small patterns with an outsized effect on how responsive an app feels. Use debounce when only the final value matters, such as search inputs and validation, and use throttle when you need steady updates during a continuous event, such as scrolling and resizing. Keep the wrapped function stable, pick a sensible delay, preserve this and arguments, and your event handlers will stay fast and predictable. Start with the short implementations in this note, test them with real typing and scrolling, and adjust the timing until the interaction feels calm rather than chatty or sluggish.




3 thoughts on “How to Debounce and Throttle Functions in JavaScript”