Problem Statement
As a Staff Engineer reviewing production performance, I frequently encounter scenarios where we need to limit the rate of function execution—especially for high-frequency events. Implement a throttle utility that ensures a function executes at most once per specified time interval.
Requirements
Implement a throttle(func, wait) function that:
- Executes
funcimmediately on the first call - Ignores subsequent calls within the
waitperiod - After the wait period, the next call executes immediately
- Preserves
thiscontext and arguments
Example Usage
Key Difference from Debounce
| Throttle | Debounce |
|---|---|
| Executes at regular intervals | Executes after activity stops |
| Guarantees execution during activity | Only executes when activity pauses |
| Use for: scroll, resize, mousemove | Use for: search input, form validation |
Real-world Context
- Scroll event handlers for infinite scroll or parallax
- Mouse move handlers for drag operations
- Rate-limiting API calls
- Game loop input handling
Follow-up Questions
- What happens to the last call if it falls within a throttle window?
- How would you ensure the last call is always executed?