Debouncing and Throttling Events
You'll learn how to limit expensive event handler execution for scroll, resize, and input events to prevent overwhelming the main thread.
The Problem
Events like scroll, resize, and input can fire dozens or even hundreds of times per second. If your event handler performs expensive operations (like calculations, DOM updates, or API calls), you'll quickly overwhelm the main thread, causing janky, unresponsive interfaces.
Two Strategies to Limit Execution
Debouncing
Debouncing delays execution until activity stops. Think of it like an elevator: it waits a few seconds after the last person enters before closing the doors.
When a user types in a search box, you don't want to query the API on every keystroke. Instead, wait until they pause typing (maybe 300ms of silence) before sending the request.
Throttling
Throttling limits execution to once per time interval, regardless of how many times the event fires. Imagine a turnstile that only lets one person through every few seconds, no matter how many people are pushing.
For scroll events updating a progress bar, you might throttle to once every 100ms—smooth enough for users, but dramatically fewer executions than the raw event stream.
When to Use Which
- Debounce: Search inputs, form validation, window resize handlers where you only care about the final state
- Throttle: Scroll position tracking, mouse movement, progress indicators where regular updates matter but not every single event
Both techniques drastically reduce main-thread pressure while maintaining good user experience.
Key Takeaway: Debouncing waits for silence before executing once; throttling executes at regular intervals. Both prevent expensive handlers from overwhelming the main thread during high-frequency events.