debounce()
debounce<
Args,Context>(func,wait,immediate): (this, ...args) =>void&object
Creates a debounced function that delays execution until after a wait period.
Type Parametersโ
Args: Args extends unknown[]โ
The argument types of the function.
Context: Context = unknownโ
The type of this context.
Parametersโ
func: (this, ...args) => voidโ
The function to debounce.
wait: numberโ
The number of milliseconds to delay.
immediate: boolean = falseโ
If true, trigger on leading edge instead of trailing edge.
Returns: (this, ...args) => void & objectโ
The debounced function with cancel() and flush() methods.
Throwsโ
RangeError If wait is negative or not finite.
Sinceโ
2.0.0
Performanceโ
Clears previous timeout on each call to prevent multiple pending executions.
Also known asโ
debounce (Lodash, es-toolkit, Remeda, Radashi, Modern Dash) ยท โ (Ramda, Effect, Antfu)
Exampleโ
// Trailing edge (default)
const search = debounce((query: string) => {
console.log(`Searching: ${query}`);
}, 300);
search('abc'); // After 300ms: "Searching: abc"
// Leading edge
const save = debounce(() => console.log('Saved'), 1000, true);
save(); // Immediately: "Saved"
// Cancel pending
search.cancel();
// Force immediate execution
search('urgent');
search.flush(); // Immediately: "Searching: urgent"
How it works?โ
Debounce delays execution until the user stops calling for a specified duration. Each call resets the timer โ only the last call triggers the function.
Debounce vs Throttleโ
Debounce waits for silence โ resets on every call. Throttle enforces rhythm โ fires at fixed intervals.
| Debounce | Throttle | |
|---|---|---|
| Fires | Once, after silence | Periodically |
| Best for | Search input | Scroll events |
Use Casesโ
Optimize search input performance ๐โ
Delay search execution until user stops typing to reduce API calls and improve performance. Essential for search interfaces and autocomplete functionality.
const search = debounce((query) => {
api.search(query);
}, 300);
// User types "hello"... only one API call after 300ms
input.on("input", (e) => search(e.target.value));
Delay API calls until idle ๐โ
Delay API requests until user stops interacting to prevent server overload. Critical for API optimization and reducing unnecessary network traffic.
const saveData = debounce((data) => {
api.save(data);
}, 1000);
// Save only after user stops editing for 1 second
editor.on("change", (data) => saveData(data));
Prevent rapid button clicksโ
Debounce button clicks to prevent accidental multiple submissions. Useful for form submissions and user interface interactions.
const submitForm = debounce(() => {
form.submit();
}, 500, true); // Immediate = true
// Only first click triggers action
button.on("click", submitForm);
Rate-limit WebSocket messages in real-time appsโ
Debounce high-frequency WebSocket messages to prevent UI overload. Critical for trading platforms, live dashboards, and real-time collaboration tools.
// Debounce price updates from trading WebSocket
const handlePriceUpdate = debounce((priceData) => {
updateTradingChart(priceData);
recalculatePortfolioValue(priceData);
}, 100);
websocket.on("price_update", (data) => {
handlePriceUpdate(data);
});
// For live chat typing indicators
const sendTypingIndicator = debounce(() => {
socket.emit("user_typing", { roomId, userId });
}, 500);
messageInput.on("input", sendTypingIndicator);
Auto-save documents while editingโ
Save document or form content automatically after the user stops typing. Essential for rich text editors, note-taking apps, and any "Google Docs-like" experience.
const autoSave = debounce(async (content: string) => {
await api.saveDraft({ content, updatedAt: Date.now() });
showSaveIndicator("Saved");
}, 2000);
editor.on("change", (content) => {
showSaveIndicator("Saving...");
autoSave(content);
});