Skip to content

Correctly typed, generic, typescript throttle function

License

Notifications You must be signed in to change notification settings

martinstark/throttle-ts

Repository files navigation

throttle-ts

Correctly typed, generic, tiny (419B), typescript throttle function.

const fn = (str: string, num: number) => `hello ${str} ${num}`;

const [throttled, cancel, reset] = throttle(fn, 500);

throttled("world", 1);

Yields the return value of the throttled function, or undefined when throttled/cancelled.

The throttled function keeps the type signature of the original function, plus undefined.

image

Returns a cancel function which enables cleanup of the timeout, and blocks future calls to the throttled function. Useful when unmounting (react) ui components.

Returns a reset function which enables clearing the timeout, letting you call the method again before the delay has expired.

Usage

npm i throttle-ts
import { throttle } from "throttle-ts";
const fn = () => "executed";

const [throttledFn] = throttle(fn, 200);

throttledFn(); // "executed"
throttledFn(); // undefined
throttledFn(); // undefined
setTimeout(throttledFn, 500); // "executed"

Using Cancel

const fn = () => "executed";

const [throttledFn, cancel] = throttle(fn, 200);

throttledFn(); // "executed"
setTimeout(throttledFn, 500); // undefined
cancel(); // blocks all future calls to the throttled function

Using Reset

const fn = () => "executed";

const [throttledFn, _, reset] = throttle(fn, 200);

throttledFn(); // "executed"
throttledFn(); // undefined
reset(); // reset delay timeout
throttledFn(); // "executed"
throttledFn(); // undefined