Debounce: attendere una pausa
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;
}
Con eventi a 0, 50, 100 e 150 ms e ritardo di 200 ms, il debounce trailing parte non prima di 350 ms se non arrivano altri eventi. Ogni chiamata sostituisce il timer. [1][3]
La funzione conserva argomenti e this dell’ultima chiamata. Accetta una callback sincrona e un ritardo intero da 0 a 2.147.483.647 ms; valori maggiori possono causare overflow del timer. cancel rimuove il lavoro in attesa, non un’operazione già iniziata. Il risultato non viene restituito. Gestire gli errori nella callback; per il lavoro asincrono vedere la sezione 4. [3]
Throttle: limitare la frequenza
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);
};
}
Con gli stessi eventi e intervallo di 200 ms, la variante leading parte a 0 ms e ignora gli altri eventi. Un evento a 250 ms viene elaborato. Senza eventi non ci sono esecuzioni. [2]
performance.now() è un orologio monotono. Non vengono creati timer né conservati argomenti ignorati. Se serve l'ultima posizione di scorrimento, usare una variante trailing.
Leading, trailing e maxWait con 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 indica l'inizio, trailing la fine. Lodash debounce usa trailing per impostazione predefinita, throttle entrambi. Con entrambe le opzioni una chiamata isolata non genera un secondo trailing. maxWait limita il rinvio continuo ma non garantisce scadenze se il ciclo degli eventi è bloccato. [4]
L’esempio richiede lodash-es, una textarea e le funzioni sincrone saveDraft, reportScroll e onError (onError non deve lanciare eccezioni). Il salvataggio avviene dopo 400 ms di pausa; maxWait di 2000 ms limita il rinvio. flushDraft esegue un salvataggio in attesa; chiamarlo prima di dispose se necessario. dispose rimuove listener e chiamate in attesa. Il completamento della rete alla chiusura non è garantito.
Ricerca in tempo reale: annullamento e risposte obsolete
<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();
};
}
Debounce non annulla richieste già inviate. Invalidare subito la revisione precedente e interrompere fetch al cambio del testo. HTTP 404 non comporta necessariamente il rigetto della promessa; verificare response.ok. [5][6]
GET /api/search?q=… deve restituire un array di oggetti {id: string, title: string}. Il modulo valida le risposte, limita la query a 100 caratteri e inserisce i risultati come testo. Dopo il caricamento HTML importare mountSearch e chiamare const dispose = mountSearch(); allo smontaggio chiamare dispose(). Durante la composizione IME annullare il lavoro precedente e attenderne la fine. La revisione protegge anche se l’annullamento non ferma tutto. I controlli client non sostituiscono la validazione server; abortire non annulla le operazioni sul server. [5][6][13]
Scorrimento e 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 sincronizza il lavoro visivo con i fotogrammi, non impone un intervallo temporale allo scroll. Per calcoli costosi usare un intervallo esplicito; per la visibilità valutare IntersectionObserver. [7][8][9]
L’elemento progress nativo con etichetta rappresenta valori da 0 a 1 senza stili inline o semantica ARIA ricostruita. Separare HTML e CSS; dopo il caricamento chiamare const progress = bindScrollProgress(); allo smontaggio progress.dispose(). Un fotogramma raggruppa gli eventi. ResizeObserver osserva contenuto e body se disponibile; chiamare progress.refresh() per modifiche geometriche non rilevate. Senza distanza di scorrimento l’esempio mostra 0. [12] [14]
Debounce 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;
}
Aggiornare subito il campo e ritardare ricerca o filtro. L'hook gestisce il timer in un effetto e lo elimina al cambio delle dipendenze o allo smontaggio, anche in Strict Mode. [10]
Il valore iniziale è immediato. Mantenere stabile l'identità degli oggetti. useDeferredValue controlla la priorità di rendering, non la frequenza delle richieste. Per annullare appena cambia il testo usare la sezione 4. [11]
L’hook TypeScript conserva il tipo del valore, anche quando è una funzione. Il ritardo deve essere un intero da 0 a 2.147.483.647 ms.
Scegliere intervalli e misurare
200–400 ms per la ricerca e 100–250 ms per i report di scroll sono punti di partenza, non standard. I timer possono ritardare con schede inattive o thread principale occupato. [3]
Confrontare eventi, esecuzioni, richieste e latenza dei risultati. Throttle non limita il numero di operazioni asincrone simultanee; debounce non sostituisce limiti server, idempotenza o blocchi di invio. Ridurre il costo del lavoro bloccante o spostarlo fuori dal thread principale.
