Overview
The throttle utilities limit how often a function can be called. Unlike debouncing which delays execution, throttling ensures a function is called at most once in a specified time period.Import
throttleByTimeout
Throttles function execution usingsetTimeout. Ensures the function is called at most once per delay period.
Signature
Parameters
The function to throttle.
The number of milliseconds to throttle invocations to.
Return Value
Example
throttleByTime
Throttles function execution based on elapsed time since the last invocation. UsesDate.now() for time tracking.
Signature
Parameters
The function to throttle.
The minimum time in milliseconds between function invocations.
Return Value
A throttled function that accepts the same parameters as the original callback.
Example
throttleByFrame
Throttles function execution to run at most once per animation frame usingrequestAnimationFrame.
Signature
Parameters
The function to throttle to animation frames.
Return Value
Example
Comparison
| Strategy | Best For | Cancellable | Timing Mechanism |
|---|---|---|---|
throttleByTimeout | Network requests, API calls | Yes | setTimeout |
throttleByTime | High-frequency events, logging | No | Date.now() |
throttleByFrame | Visual updates, animations | Yes | requestAnimationFrame |
Common Use Cases
throttleByTimeout
- API rate limiting
- Button click protection
- Form submission throttling
throttleByTime
- Scroll event handlers
- Mouse move tracking
- Keyboard input logging
throttleByFrame
- Scroll-based animations
- Drag and drop operations
- Canvas rendering
- Parallax effects
Notes
- throttleByTimeout: Executes after the delay period, suitable for async operations
- throttleByTime: Executes immediately if enough time has passed, best for real-time tracking
- throttleByFrame: Syncs with browser repaint cycle (~60fps), optimal for smooth animations
- All throttle functions preserve the original function’s parameters and type safety