Difference between JavaScript debounce and throttle: when to use which one?
Use debounce on the search field and throttle on the scroll event; See examples of leading, trailing, maxWait, cancel, and managing legacy API responses.
Debounce, waits for a certain period of silence after frequent events.Throttleallows the function to run at specified intervals while events are ongoing. Generally, debounce is selected in the search box and throttle is selected to track scroll position.
Both methods can reduce the workload of heavy event flow. But their behavior is different: do you wait for the user's last value, or do regular updates as the transaction continues? Making the choice with this question is more useful than just memorizing the names.
How does the outcome change in the same sequence of events?
Consider that events arrive at 0, 80, 160 and 240 milliseconds, with a waiting interval of 300 ms. Trailing debounce renews the wait as new events arrive and runs with the last value approximately 300 ms after the last event.
If leading and trailing are open throttle, the first event can be processed immediately; It does not run other events one by one during this period and may call trailing for the last value at the end of the interval. The actual running time of schedulers is affected by event loop and background tab constraints; These mechanisms are not precise time clocks.
| Need | Start selection | From where? |
|---|---|---|
| Search after post ends | Debounce | It puts intermediate queries on hold. |
| Regular position reading while scrolling | Throttle | Updates the event stream as it progresses. |
| Automatic save after change | Debounce + maxWait | Silence awaits; in continuous regulation it is not postponed indefinitely. |
| Visual update with keyframes | requestAnimationFrame | Maps visual work to browser frames. |
1. Add debounce to search field with Lodash
examples,lodashIt is for the bundler project that is installed and supports module import. The naive browser module does not resolve this package name by itself. In the relevant HTMLid="search"which is input andid="results"There must be a result field.
import debounce from "lodash/debounce.js";
const input = document.querySelector("#search");
const results = document.querySelector("#results");
let revision = 0;
let controller;
const search = debounce(async (query, requestRevision) => {
controller = new AbortController();
try {
const response = await fetch(
`/api/search?q=${encodeURIComponent(query)}`,
{ signal: controller.signal }
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (requestRevision !== revision) return;
// Ornek API sozlesmesi: { items: [{ title: "..." }] }
results.textContent = data.items.map(item => item.title).join(", ");
} catch (error) {
if (error.name !== "AbortError" && requestRevision === revision) {
results.textContent = "Arama tamamlanamadı.";
}
}
}, 300);
function onInput(event) {
const query = event.target.value.trim();
revision += 1;
controller?.abort();
if (query.length < 2) {
search.cancel();
results.textContent = "";
return;
}
search(query, revision);
}
input.addEventListener("input", onInput);
// Ekran kaldirildiginda lifecycle tarafindan cagrilir.
function disposeSearch() {
input.removeEventListener("input", onInput);
revision += 1;
search.cancel();
controller?.abort();
}
Debounce only manages call frequency; It does not cancel the network request that has started. The above AbortController tries to stop the previous request. Revision control prevents the old answer, which was completed without being canceled, from overwhelming the new search result. When the user frees the space, both the pending call and the previous request are cleared.
2. Use throttle on scroll event
import throttle from "lodash/throttle.js";
const position = document.querySelector("#position");
const onScroll = throttle(() => {
position.textContent = `${Math.round(window.scrollY)} px`;
}, 200, { leading: true, trailing: true });
window.addEventListener("scroll", onScroll, { passive: true });
function disposeScroll() {
window.removeEventListener("scroll", onScroll);
onScroll.cancel();
}
In this exampleid="position"An area is required. The Passive option specifies that the listener will not use preventDefault; It does not automatically make the expensive work done by the function cheaper. Performing intensive DOM queries or large calculations on each call can again impact performance.
3. When are leading, trailing and maxWait required?
leadingAt the beginning of the waiting interval,trailingfinally controls the call behavior. Lodash debounce runs trailing by default; throttle opens both by default. Do not assume that a single event will necessarily generate two calls when both are on; repetitions within the range affect behavior.
maxWaitis the upper waiting limit for debounce that prevents incoming events from delaying execution indefinitely. For example, in automatic recording, 500 ms of silence and a maximum of 5 seconds of waiting may be considered. These values should be chosen according to the behavior of the product; Automatic recording also requires error management and recording ordering.
4. Clear pending job when screen turns off
cancel()removes the waiting call.flush()Executes the pending trailing call immediately. Don't rely on flush to assume that the network request will complete as the page closes; For automatic registration, the life cycle of the application and, if necessary, a different delivery method should be planned.
Recreating the debounced function in React or another UI framework with each render can create timers that are independent of each other. Keep the function ID stable, determine how it reads the current state, and abort it in the unmount cleanup.
Short guide
Common mistake
Considering Debounce the only guarantee for double payments or double form submissions. In this case, button state, server authentication and, if necessary, idempotency mechanism are also required.