throttle
Creates a throttled function that limits invocations to a specified interval
Usage
The throttle
function creates a new function that, when called, will only execute the original function at most once per specified time interval. This is useful for limiting the rate at which a function can fire, especially for performance-intensive operations like handling scroll or resize events.
The function accepts two parameters:
- An options object with:
interval
: The minimum time (in milliseconds) between function invocationstrailing
(optional): If true, also calls the function after the throttle period if it was invoked during the throttle
- The function to be throttled
The returned throttled function also includes these methods:
isThrottled(): boolean
: To check if there’s currently an active throttletrigger(...args): void
: To invoke the wrapped function without waiting for the next interval
Timing
A visual representation of the throttle behavior when interval
is set to 200ms
:
When the trailing
option is set to true
, an additional invocation occurs after the throttle period if any calls were made during the throttled time:
In this diagram, ‘x’ represents function invocations, and ’-’ represents time passing.