Skip to the content.

Delay utilities

Utilities for delaying function calls.

import { throttle, delay } from "@travisspomer/tidbits"

// Prints "Hello!" ten times.
const myFunction = () => { console.log("Hello!") }
for (i = 0; i < 10; i++) myFunction()

// Prints "Hello!" twice: once immediately, and once after 1 second passes.
const myThrottledFunction = throttle(1000, myFunction)
for (i = 0; i < 10; i++) myThrottledFunction()

// Prints "Hello!" once after 1 second passes.
const myDelayedFunction = throttle(1000, myFunction)
for (i = 0; i < 10; i++) myDelayedFunction()

throttle and delay

throttle(interval: number, func: () => void): () => void
delay(interval: number, func: () => void): () => void

If you're not sure which one you want, just try both and see which one feels better: probably throttle.

Note that this is not a debounce function. For example, if the interval is 1 second (1000), and the function is called repeatedly over the course of 5.5 seconds, func will still get called up to 6 times. A traditional debounce function would reset the timer on each call, so func would only get called once at the very end.

The return value of func will be lost. Parameters passed to the wrapper function will be passed to func, but keep in mind that since some calls to func are skipped, some sets of parameters are necessarily ignored. The parameters are also ignored when deciding whether to call func. Thus, these functions cannot be used to implement a feature like how the browser groups calls with identical arguments to console.log().

You should never call throttle or delay itself in a loop: both methods return a new function that encapsulates the delay logic.

// This won't work as expected:
for (i = 0; i < 10; i++) throttle(1000, () => console.log("Hello!"))