Throttling
A technique that limits the execution of a function to at most once in a specified period of time.
Detailed Explanation
Unlike debouncing (which waits for a pause), throttling ensures that a function executes at a regular interval. This is ideal for events that fire continuously, like scrolling or resizing the window. For example, you might throttle a scroll listener to run only once every 100ms. This prevents the browser from becoming overwhelmed by a flood of events.
Quick Summary
Throttling caps how often a function can run, at most one call per interval, no matter how many events arrive in between. It keeps UI responsive when events stream continuously, like scrolling, dragging, or pointer-move.
Key Takeaways
- Throttle guarantees a steady call rate; debounce guarantees one call after a pause. They solve different problems.
- Common windows: 16 ms (~60 fps) for animation, 100 ms for scroll handlers, 1 s for analytics beacons.
- Leading-edge throttle fires immediately and ignores the rest; trailing-edge fires at the end of the window so the last value is captured.
- requestAnimationFrame is a natural throttle for visual work, the browser already paces it to the display refresh.
- Server-side, rate limiting is throttling applied per client to protect APIs from abuse.
When to use it
- Scroll handlers that drive parallax, sticky headers, or lazy-load triggers.
- Mouse/touch move listeners powering drag-and-drop or canvas drawing.
- Analytics events (scroll depth, viewport time) that would otherwise flood the network.
- API client retry/back-off loops that must not hammer a struggling backend.
Common Mistakes
- Throttling user input where you actually want the final value, that's debounce, not throttle.
- Setting the interval below one animation frame (~16 ms), wasting CPU without visible benefit.
- Throttling on the leading edge only, so the user's final action gets dropped and the UI feels "stuck."
- Recreating the throttled function on every render so each instance has its own internal clock and nothing is actually throttled.
Throttling, Frequently Asked
Throttle or requestAnimationFrame for scroll effects?
Prefer requestAnimationFrame for anything that draws to the screen, it syncs with paint and skips work when the tab is hidden. Use a time-based throttle when you are sending network requests or doing non-visual work that should run at a steady rate even off-screen.
Does throttle drop events or queue them?
Standard throttle drops intermediate events and only fires at the next allowed interval, usually with the latest arguments. Queueing every event is a different pattern (a rate-limited queue) and is rare on the client.
How does throttling interact with React state?
If a throttled callback closes over state, it sees the state from the render where it was created. Use refs or pass arguments explicitly to ensure the callback acts on the current value rather than a stale snapshot.