State & ArchitectureBaseline · Widely

Debounce, Throttle & rAF Coalescing

Mental Model

High-rate gaming mice fire pointermove at 240+ Hz, while displays only paint at 60–120 Hz. Use debounce to wait for a pause (search API calls), throttle to cap steady-state frequency (analytics pings), and rAF coalescing to fold multiple visual updates into one VSync frame.

Interactive Simulator

Event Rate Limiting: Debounce vs Throttle vs rAF

Compare how burst pointer/key events map to handler invocations under each coalescing strategy.

Parameter Profile
strategyraf-coalesce
inputBurstHz120
cancelOnUnmountOn
strategy
raf-coalesce
inputBurstHz
120
cancelOnUnmount
On
Parameters evaluated in real time.

Under the Hood

Firing a DOM mutation on every pointermove event is like repainting a billboard 240 times a second when the camera shutter only opens 60 times. Each strategy hooks a different phase of the Event Loop and Browser Rendering Pipeline:

  • Debounce: Resets a setTimeout on every event; executes once after N ms of silence.
  • Throttle: Executes at most once per N ms window using a timestamp or cooldown timer.
  • rAF Coalescing: Stores the latest coordinates in a variable and schedules a single requestAnimationFrame if one isn't already pending, always matching the monitor's exact refresh rate and pausing in background tabs.
JS
let pendingFrame = 0;
let latestX = 0;

window.addEventListener('pointermove', (e) => {
  latestX = e.clientX;
  if (pendingFrame) return; // Coalesce until next VSync
  pendingFrame = requestAnimationFrame(() => {
    pendingFrame = 0;
    slider.style.transform = `translateX(${latestX}px)`;
  });
});

Problem Genealogy

  • 2009 (jQuery Scroll/Resize Handlers): Ran synchronously on every pixel scrolled, freezing browsers until developers bolted on Underscore _.debounce and _.throttle.
  • 2013 (requestAnimationFrame Standardization): Replaced setTimeout(..., 16) hacks that drifted against 60 Hz and 120 Hz VSync intervals.
  • 2016+ (ResizeObserver & IntersectionObserver): Moved common scroll/resize polling natively into the browser's frame lifecycle.

Production Pitfalls

Production Pitfall
  • Debouncing controlled <input> state: Delaying the text box's own value state makes typing feel broken; update the input synchronously and debounce only the side-effect query.
  • Uncancelled timers on unmount: Leaving a 300 ms debounced save() pending after a user navigates away triggers Stale Closures or writes to unmounted state, always call clearTimeout / cancelAnimationFrame on cleanup.
When Not to Use
  • When not to use throttling: Never throttle discrete state-machine inputs (keydown Enter, form submit, or click toggles), dropping or delaying discrete user intent feels like a broken button.

Connections & Logical Next Steps

Seen in Architecture Autopsies

Mechanical Comparisons