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
const trackScroll = (scrollPos) => {
console.log(`Scroll position: ${scrollPos}`);
};
const throttledScroll = throttle(trackScroll, 100);
// User scrolls rapidly (event fires every 10ms)
// t=0ms: throttledScroll(0); // Logs: "Scroll position: 0"
// t=10ms: throttledScroll(50); // Ignored
// t=20ms: throttledScroll(100); // Ignored
// ...
// t=100ms: throttledScroll(500); // Logs: "Scroll position: 500"
// t=110ms: throttledScroll(550); // Ignored
// t=200ms: throttledScroll(900); // Logs: "Scroll position: 900"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?