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
import * as _ from 'radashi'
// Throttle a scroll event handlerconst handleScroll = () => { console.log('Scroll position:', window.scrollY)}const throttledScroll = _.throttle({ interval: 200 }, handleScroll)window.addEventListener('scroll', throttledScroll)
// Throttle an API callconst throttledFetch = _.throttle( { interval: 5000, trailing: true }, async () => { const response = await fetch('https://api.example.com/data') const data = await response.json() console.log(data) },)
// Check if throttledconsole.log('Is throttled:', throttledFetch.isThrottled())
Timing
A visual representation of the throttle behavior when interval
is set to 200ms
:
Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -Throttle Invocations: x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x - - -Source Invocations: x - - - - - - - - - - - - x - - - - - - - - - - - - - x - - - - - -
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:
Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -Throttle Invocations: x x x x x x x x x x x x x x x x x x x x x - - - - - - - - - - - - -Source Invocations: x - - - - - - - - - - - - x - - - - - - - - - - - - - x - - - - - -
In this diagram, ‘x’ represents function invocations, and ’-’ represents time passing.