debounce
debounce creates a debounced function that delays execution until after a specified wait time has elapsed since the last call. It wraps DebounceTaskExecutor for function-level use.
Best for function-level debouncing Use
debouncewhen you want to debounce a standalone function rather than managing an executor.
Import
Section titled “Import”Root package:
import { debounce } from "@vgerbot/async";Module subpath:
import { debounce } from "@vgerbot/async/utils";Leaf subpath:
import { debounce } from "@vgerbot/async/utils/debounce";Quick example
Section titled “Quick example”import { debounce } from "@vgerbot/async";
const search = debounce( async (query: string) => { const res = await fetch(`/api/search?q=${query}`); return res.json(); }, 300, // 300ms wait);
// Rapid calls — only the last one executessearch("he");search("hel");search("hell");search("hello");
// After 300ms of no calls, search("hello") executesWhen to use debounce
Section titled “When to use debounce”- Search-as-you-type: Debounce search requests while the user is typing.
- Autosave: Debounce save operations while content is changing.
- Resize handlers: Debounce layout recalculations.
- Form validation: Debounce validation checks as the user edits.
function debounce<T, Args extends unknown[] = unknown[]>( fn: (...args: Args) => Promise<T>, wait: number, options?: DebounceOptions,): DebouncedFunction<T, Args>;DebouncedFunction
Section titled “DebouncedFunction”interface DebouncedFunction<T, Args extends unknown[] = unknown[]> { (...args: Args): Promise<T>; cancel(): void; flush(): void; pending(): boolean;}Parameters
Section titled “Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
fn |
(...args: Args) => Promise<T> |
— | Async function to debounce. |
wait |
number |
— | Milliseconds to wait before executing. |
options |
DebounceOptions |
undefined |
Debounce configuration. |
DebounceOptions
Section titled “DebounceOptions”| Option | Type | Default | Description |
|---|---|---|---|
leading |
boolean |
false |
Execute on the leading edge (first call). |
trailing |
boolean |
true |
Execute on the trailing edge (after wait). |
maxWait |
number |
undefined |
Maximum wait time before forced execution. |
Return value
Section titled “Return value”Returns a debounced function with cancel(), flush(), and pending() methods.
| Method | Description |
| — | — | — |
| cancel() | Cancels the pending execution. |
| flush() | Immediately executes the pending task. |
| pending() | Returns true if a task is waiting to execute. |
Execution model
Section titled “Execution model”debounce creates a DebounceTaskExecutor internally. Each call to the debounced function submits a new task to the executor, which replaces any pending task.
const save = debounce(async (data: string) => { await fetch("/api/save", { method: "POST", body: data });}, 500);
// User types rapidlysave("draft 1");save("draft 2");save("draft 3");
// Only "draft 3" is saved after 500ms of inactivityLeading edge
Section titled “Leading edge”const log = debounce( async (msg: string) => console.log(msg), 1000, { leading: true, trailing: false },);
log("first"); // Executes immediatelylog("second"); // Droppedlog("third"); // Dropped
// Only "first" is loggedCancellation
Section titled “Cancellation”const search = debounce(mySearchFn, 300);
search("query");search.cancel(); // Pending search is cancelled
if (search.pending()) { search.flush(); // Execute immediately}TypeScript tips
Section titled “TypeScript tips”debounce preserves the argument types of the original function.
const fn = (a: number, b: string): Promise<boolean> => { /* ... */ };const debounced = debounce(fn, 300);
const result = await debounced(42, "hello"); // Promise<boolean>Related APIs
Section titled “Related APIs”DebounceTaskExecutor— the executor backing this function.throttle— function-level throttle.ThrottleTaskExecutor— throttle executor.once— execute a function only once.