← Back to Engine

Performance: Debouncing & Throttling


Uncontrolled event listeners on high-frequency DOM events (like scroll, resize, and keyup) can trigger thousands of executions per second, overwhelming the main thread and causing severe UI lag (layout thrashing).

1. Debouncing (Quiet Period Trigger)

Debouncing postpones function execution until a specified quiet period (e.g. 300ms) has elapsed since the last invocation. Every new call resets the timer. Perfect for search input autocomplete and window resize recalculations.

2. Throttling (Fixed Rate Limiting)

Throttling enforces a maximum execution frequency (e.g. once every 100ms), ignoring intermediate calls during the cooldown window. Perfect for infinite scrolling, game loops, and button mash prevention.


The Challenge: Implement Debounce & Throttle

Implement two higher-order rate limiting utilities from scratch:

  1. debounce(fn, delay): Uses clearTimeout and setTimeout to collapse rapid bursts into a single trailing execution.
  2. throttle(fn, limit): Uses timestamp tracking or a boolean lock to guarantee execution at most once per limit milliseconds.