Debounce & Throttle
Performance Optimization: Control the rate at which functions are executed to improve performance
1. Debounce Concept
Debouncing ensures that a function is only called after a certain amount of time has passed without it being called again.
Real World Examples:
- Search input suggestions
- Window resize events
- Auto-save functionality
- Form validation on typing
When to Use:
- When you want to wait until user stops typing
- For expensive operations triggered by frequent events
- When you need to reduce API calls
Basic Debounce Implementation
JavaScript Editor
Debounce with Immediate Option
Sometimes you want to execute immediately on the first call, then debounce subsequent calls.
JavaScript Editor
2. Throttle Concept
Throttling ensures that a function is called at most once in a specified time period.
Real World Examples:
- Scroll event handlers
- Mouse move events
- Window resize with complex calculations
- Game button presses
When to Use:
- When you need to limit the rate of execution
- For continuous events like scrolling/resizing
- When you want regular updates but not too frequent
Basic Throttle Implementation
JavaScript Editor
Throttle with Leading and Trailing Options
JavaScript Editor
3. Comparison & Use Cases
| Feature | Debounce | Throttle |
|---|---|---|
| Execution Timing | After the event stops for X time | At most once every X time |
| Use Case Example | Search on typing | Scroll event handling |
| Response Time | Delayed response | Immediate first response |
| Event Frequency | Reduces to single call | Reduces frequency |
| Memory Usage | Stores timeout | Stores last execution time |
4. Practical Examples
Example 1: Search Input with API Call
JavaScript Editor
Example 2: Infinite Scroll with Throttle
JavaScript Editor
Example 3: Resize Handler with Both
JavaScript Editor
5. Advanced Implementation
Cancelable Debounce
JavaScript Editor
Best Practices:
- Use debounce for user input events (typing, searching)
- Use throttle for continuous events (scrolling, resizing)
- Adjust delay times based on use case (300-500ms for typing, 100-200ms for scrolling)
- Consider memory cleanup by canceling timeouts when components unmount
- Test with different network conditions and device performance