Skip to content

throttle

Creates a throttled function that limits invocations to a specified interval

260 bytes

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:

  1. An options object with:
    • interval: The minimum time (in milliseconds) between function invocations
    • trailing (optional): If true, also calls the function after the throttle period if it was invoked during the throttle
  2. The function to be throttled

The returned throttled function also includes these methods:

  • isThrottled(): boolean: To check if there’s currently an active throttle
  • trigger(...args): void: To invoke the wrapped function without waiting for the next interval
import { throttle } from 'radashi'
// Throttle a scroll event handler
const handleScroll = () => {
console.log('Scroll position:', window.scrollY)
}
const throttledScroll = throttle({ interval: 200 }, handleScroll)
window.addEventListener('scroll', throttledScroll)
// Throttle an API call
const 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 throttled
console.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.