How to debounce and throttle event handlers in JavaScript
· Category: JavaScript
Short answer
Debounce delays a function until after a pause in events; throttle limits execution to once per fixed interval. Both reduce unnecessary computations for high-frequency events like scroll, resize, and input.
Details
A debounce implementation stores a timer ID and resets it each time the event fires. When the timer finally expires, the wrapped function runs. Throttle uses a timestamp or boolean flag to ensure the function runs at most once per interval, firing immediately (leading) or at the end (trailing).
These techniques are essential for performance. For example, attaching an uncapped scroll listener can tank frame rates. If you are building scroll-based UIs such as infinite scroll with Intersection Observer, debouncing or throttling companion logic can keep the experience smooth.
Tips
- Use debounce for search inputs where you only need the final value.
- Use throttle for scroll or resize listeners where you want periodic updates.
- For a deeper understanding of execution timing, read about what is the JavaScript event loop and how does it work.
- Consider how to use async/await if your debounced handler performs asynchronous work like API calls.