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);
});