Debounce: run after a quiet period
const MAX_TIMEOUT_MS = 2_147_483_647;
export function debounce(callback, delay) {
if (typeof callback !== "function") {
throw new TypeError("Expected a callback function.");
}
if (!Number.isInteger(delay) || delay < 0 || delay > MAX_TIMEOUT_MS) {
throw new RangeError("Invalid debounce delay.");
}
let timeoutId;
function cancel() {
clearTimeout(timeoutId);
timeoutId = undefined;
}
function debounced(...args) {
cancel();
timeoutId = setTimeout(() => {
timeoutId = undefined;
callback.apply(this, args);
}, delay);
}
debounced.cancel = cancel;
return debounced;
}
Suppose events arrive at 0, 50, 100 and 150 ms with a 200 ms delay. A trailing debounce runs no earlier than 350 ms if no further event arrives. Each invocation replaces the previous timer. [1][3]
The implementation preserves the last call’s arguments and receiver. It accepts a synchronous callback and an integer delay from 0 to 2,147,483,647 ms; larger values may overflow the timer. cancel removes pending work, not an operation already started. The wrapper does not return the callback result. Handle errors inside the callback; use section 4 for asynchronous work. [3]
Throttle: limit execution frequency
export function throttleLeading(callback, interval) {
if (typeof callback !== "function") {
throw new TypeError("Expected a callback function.");
}
if (!Number.isFinite(interval) || interval < 0) {
throw new RangeError("Invalid throttle interval.");
}
let lastRun = -Infinity;
return function throttled(...args) {
const now = performance.now();
if (now - lastRun < interval) {
return;
}
lastRun = now;
callback.apply(this, args);
};
}
With the same events and a 200 ms interval, a leading-only throttle runs at 0 ms and skips the remaining events. Another event at 250 ms runs immediately. It is event-driven, not a periodic clock. [2]
The example uses the monotonic performance.now() clock. It creates no timers and retains no skipped arguments. This is suitable for sampling scroll position when the final skipped value is dispensable. Use a trailing variant if the final value matters.
Leading, trailing and maxWait with Lodash
import { debounce, throttle } from "lodash-es";
const DRAFT_DELAY_MS = 400;
const DRAFT_MAX_WAIT_MS = 2_000;
const SCROLL_INTERVAL_MS = 200;
export function bindDraftAndScroll(
editor,
{ saveDraft, reportScroll, onError },
) {
if (!(editor instanceof HTMLTextAreaElement)) {
throw new TypeError("Expected a draft textarea.");
}
if ([saveDraft, reportScroll, onError].some((fn) => typeof fn !== "function")) {
throw new TypeError("Expected synchronous callbacks.");
}
function save() {
try {
saveDraft(editor.value);
} catch (error) {
onError(error);
}
}
function report() {
try {
reportScroll(window.scrollY);
} catch (error) {
onError(error);
}
}
const saveLater = debounce(save, DRAFT_DELAY_MS, {
maxWait: DRAFT_MAX_WAIT_MS,
});
const reportLater = throttle(report, SCROLL_INTERVAL_MS, {
leading: true,
trailing: true,
});
const listeners = new AbortController();
editor.addEventListener("input", saveLater, { signal: listeners.signal });
window.addEventListener("scroll", reportLater, {
passive: true,
signal: listeners.signal,
});
return {
flushDraft() {
saveLater.flush();
},
dispose() {
listeners.abort();
saveLater.cancel();
reportLater.cancel();
},
};
}
Leading runs at the start of a burst; trailing runs at its end. Lodash debounce defaults to trailing, while throttle defaults to both edges. When both edges are enabled, a single call does not trigger an additional trailing invocation. maxWait limits debounce postponement under sustained input but cannot guarantee a deadline if the event loop is blocked. [4]
This example requires lodash-es, a textarea and synchronous saveDraft, reportScroll and onError callbacks (onError must not throw). Saving waits for 400 ms of quiet, with maxWait of 2000 ms limiting postponement. flushDraft executes a pending save; call it before dispose if the draft must survive. dispose removes listeners and discards pending calls. Do not assume a network request will finish on page exit.
Live search: cancellation and stale responses
<section aria-labelledby="search-heading">
<h2 id="search-heading">Product search</h2>
<label for="product-query">Search products</label>
<input id="product-query" type="search" maxlength="100" />
<p id="search-status" role="status"></p>
<ul id="search-results"></ul>
</section>
const SEARCH_DELAY_MS = 300;
const SEARCH_ENDPOINT = "/api/search";
const MAX_QUERY_LENGTH = 100;
function parseResults(payload) {
if (
!Array.isArray(payload) ||
!payload.every(
(item) =>
item !== null &&
typeof item === "object" &&
typeof item.id === "string" &&
typeof item.title === "string",
)
) {
throw new TypeError("Invalid search response.");
}
return payload.map(({ id, title }) => ({ id, title }));
}
export function createSearch({ onResults, onError }) {
if ([onResults, onError].some((callback) => typeof callback !== "function")) {
throw new TypeError("Expected search callbacks.");
}
let timeoutId;
let controller;
let revision = 0;
function cancel() {
revision += 1;
clearTimeout(timeoutId);
timeoutId = undefined;
controller?.abort();
controller = undefined;
}
async function run(query, requestRevision) {
const requestController = new AbortController();
controller = requestController;
let results;
try {
const params = new URLSearchParams({ q: query });
const response = await fetch(`${SEARCH_ENDPOINT}?${params}`, {
signal: requestController.signal,
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
results = parseResults(await response.json());
} catch (error) {
if (
requestRevision === revision &&
!requestController.signal.aborted
) {
onError(error);
}
return;
} finally {
if (controller === requestController) {
controller = undefined;
}
}
if (requestRevision === revision && !requestController.signal.aborted) {
onResults(results);
}
}
function search(value) {
cancel();
const query = value.trim();
if (!query) {
onResults([]);
return;
}
if (query.length > MAX_QUERY_LENGTH) {
onError(new RangeError("Search query is too long."));
return;
}
const requestRevision = revision;
timeoutId = setTimeout(() => {
timeoutId = undefined;
run(query, requestRevision).catch((error) => {
// Unexpected integration error, not a failed search response.
console.error(error);
});
}, SEARCH_DELAY_MS);
}
return { search, cancel };
}
export function mountSearch(root = document) {
const input = root.querySelector("#product-query");
const status = root.querySelector("#search-status");
const list = root.querySelector("#search-results");
if (
!(input instanceof HTMLInputElement) ||
!(status instanceof HTMLElement) ||
!(list instanceof HTMLUListElement)
) {
throw new Error("Missing search controls.");
}
const listeners = new AbortController();
const { search, cancel } = createSearch({
onResults(results) {
const fragment = list.ownerDocument.createDocumentFragment();
for (const { title } of results) {
const item = list.ownerDocument.createElement("li");
item.textContent = title;
fragment.append(item);
}
list.replaceChildren(fragment);
status.textContent = input.value.trim()
? `${results.length} results.`
: "Enter a search term.";
},
onError() {
status.textContent = "Search failed. Please try again.";
},
});
function pauseSearch() {
cancel();
list.replaceChildren();
status.textContent = "";
}
function updateQuery() {
list.replaceChildren();
status.textContent = input.value.trim() ? "Searching…" : "";
search(input.value);
}
function handleInput(event) {
if (event.isComposing) {
pauseSearch();
return;
}
updateQuery();
}
input.addEventListener("input", handleInput, { signal: listeners.signal });
input.addEventListener("compositionstart", pauseSearch, {
signal: listeners.signal,
});
input.addEventListener("compositionend", updateQuery, {
signal: listeners.signal,
});
updateQuery();
return () => {
listeners.abort();
cancel();
};
}
Debouncing does not cancel requests already sent. Invalidate the previous revision and abort its fetch as soon as input changes, rather than waiting for the next timer. Check response.ok because HTTP 404 does not necessarily reject the fetch promise. [5][6]
GET /api/search?q=… must return an array of objects {id: string, title: string}. The module validates responses, limits queries to 100 characters and inserts results as text. After loading the HTML, import mountSearch and call const dispose = mountSearch(); call dispose() on teardown. During IME composition, cancel stale work and wait for composition to finish. A revision guard protects even when cancellation does not stop the work. Client limits and validation do not replace server checks; aborting does not undo server operations. [5][6][13]
Scroll and requestAnimationFrame
<header class="reading-header">
<label for="reading-progress">Reading progress</label>
<progress id="reading-progress" max="1" value="0"></progress>
</header>
<main id="reading-content" class="reading-content">
<article>
<h1>Building responsive interfaces</h1>
<p>Keep event handlers small and measure expensive work.</p>
<h2>Scheduling updates</h2>
<p>Group visual updates into animation frames.</p>
<h2>Choosing an interval</h2>
<p>Measure latency and select an interval for your use case.</p>
</article>
</main>
.reading-header {
position: sticky;
inset-block-start: 0;
display: grid;
gap: 0.5rem;
padding: 1rem;
background-color: Canvas;
color: CanvasText;
border-block-end: 1px solid currentColor;
}
.reading-header progress {
inline-size: 100%;
block-size: 0.75rem;
accent-color: #2563eb;
}
.reading-content {
max-inline-size: 65ch;
margin-inline: auto;
padding: 1rem;
}
export function bindScrollProgress(root = document) {
const progressBar = root.querySelector("#reading-progress");
const content = root.querySelector("#reading-content");
const scrollingElement = document.scrollingElement;
if (
!(progressBar instanceof HTMLProgressElement) ||
!(content instanceof HTMLElement) ||
!scrollingElement
) {
throw new Error("Missing reading progress controls.");
}
let frameId = null;
let disposed = false;
const listeners = new AbortController();
function update() {
frameId = null;
const distance =
scrollingElement.scrollHeight - scrollingElement.clientHeight;
const progress = distance > 0 ? scrollingElement.scrollTop / distance : 0;
const ratio = Math.max(0, Math.min(1, progress));
progressBar.value = ratio * progressBar.max;
}
function scheduleUpdate() {
if (!disposed && frameId === null) {
frameId = requestAnimationFrame(update);
}
}
window.addEventListener("scroll", scheduleUpdate, {
passive: true,
signal: listeners.signal,
});
window.addEventListener("resize", scheduleUpdate, {
signal: listeners.signal,
});
let resizeObserver;
if (typeof ResizeObserver === "function") {
resizeObserver = new ResizeObserver(scheduleUpdate);
resizeObserver.observe(content);
resizeObserver.observe(document.body);
}
scheduleUpdate();
return {
refresh: scheduleUpdate,
dispose() {
disposed = true;
listeners.abort();
resizeObserver?.disconnect();
if (frameId !== null) {
cancelAnimationFrame(frameId);
frameId = null;
}
},
};
}
requestAnimationFrame aligns visual changes with rendering frames. It is not a time-based scroll throttle: scroll events can arrive at a similar rate to animation frames. For expensive computations use an explicit time interval; for visibility thresholds consider IntersectionObserver. [7][8][9]
A labelled native progress element represents a number from 0 to 1 without inline styling or recreating its semantics with ARIA. Keep HTML and CSS in separate files; after loading the document call const progress = bindScrollProgress(); call progress.dispose() on teardown. A single frame coalesces events. ResizeObserver observes content and body when available; call progress.refresh() for geometry changes the observer does not detect. A page with no scrollable distance reports 0 in this example. [12] [14]
Debouncing in React
import { useEffect, useState } from "react";
const MAX_TIMEOUT_MS = 2_147_483_647;
export function useDebouncedValue<Value>(value: Value, delay: number): Value {
if (!Number.isInteger(delay) || delay < 0 || delay > MAX_TIMEOUT_MS) {
throw new RangeError("Invalid debounce delay.");
}
const [debouncedValue, setDebouncedValue] = useState<Value>(() => value);
useEffect(() => {
const timeoutId = setTimeout(() => {
setDebouncedValue(() => value);
}, delay);
return () => {
clearTimeout(timeoutId);
};
}, [value, delay]);
return debouncedValue;
}
Update text input state immediately, but expensive filtering or searching can depend on a delayed value. The custom hook stores a timer in an effect and clears it on dependency changes or unmount. The Strict Mode setup-cleanup cycle therefore does not leave the old timer running. [10]
The hook returns the initial value immediately and delays later changes. Keep object identities stable to avoid restarting the timer on every render. useDeferredValue controls rendering priority, not request frequency. If old requests must be canceled at the instant input changes, use the mechanism in section 4 rather than only a delayed value. [11]
The TypeScript hook preserves the value type, including function values. The delay must be an integer from 0 to 2,147,483,647 ms.
Selecting delays and measuring results
200–400 ms for search and 100–250 ms for occasional scroll reporting are possible experimental starting points, not universal standards. Timers specify an earliest opportunity, not a guaranteed execution deadline. Background tabs and a busy main thread can delay execution. [3]
Compare event counts, actual callback counts, network requests and time from the last input to results. Throttle does not cap simultaneous asynchronous operations, and debounce is no substitute for server rate limits, idempotency or submit locking. If one callback still blocks the interface, reduce its cost or move computations off the main thread.
