Debounce
A rate-limiting technique that delays execution until a burst of rapid events has paused for a specified wait time
Table of Contents
Interactive Playground
Tap or drag to interact with the demoWhat is Debounce?
A rate-limiting technique that delays execution until a burst of rapid events has paused for a specified wait time. It is a core concept in Performance & Optimization within Web Dev.
Core Principles
Debouncing controls high-frequency event streams—such as keystrokes in a search bar or window resize events—by resetting a countdown timer every time a new event fires. The target callback runs only once, after the stream stays quiet for the configured wait duration (e.g., 300ms).
Unlike Throttling, which guarantees execution at steady intervals during continuous activity (ideal for scroll tracking), Debouncing collapses a noisy burst into a single final execution once the user finishes acting.
Practical Takeaways
- Tune the delay to the interaction: Search autocomplete feels snappy yet server-friendly around
200–300ms, while heavier background auto-saves work best at800–1500ms. - Know Leading vs. Trailing edge: Standard trailing debounce waits until input stops. For double-submit prevention on payment or save buttons, use leading-edge debounce so the first click fires immediately while accidental rapid clicks are ignored.
- Clean up timers and stale requests: In React or Vue, cancel pending timers on unmount and pair debounced fetches with
AbortControllerto avoid race conditions from out-of-order network responses.
Notable Examples
- Search Autocomplete: Typing
"typescript"triggers 1 API request after a brief pause instead of 10 redundant queries. - Window Resize Recalculation: Recomputes heavy canvas or chart layouts once the user finishes dragging the viewport edge.
- Cloud Document Auto-Save: Syncs edits only after the writer pauses typing for a second, cutting write traffic dramatically.
Practical Code Snippet
Copy and drop straight into your projectexport function debounce<T extends (...args: unknown[]) => void>( fn: T, delayMs = 300) { let timer: ReturnType<typeof setTimeout> | undefined; return (...args: Parameters<T>) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delayMs); };} // Usage: fires once 300ms after the user stops typingconst onSearch = debounce((query: string) => { fetch(`/api/search?q=${encodeURIComponent(query)}`);}, 300);