throttle

Return a throttled function that invokes the passed function at most once per every `given` milliseconds.

1.
/**
2.
* Return a throttled function that invokes the passed function at most once per every `given` milliseconds.
3.
**/
4.
5.
function throttle<A extends any[]>(
6.
fn: (...args: A) => void,
7.
limit: number,
8.
): (...args: A) => void {
9.
let lastCall = 0;
10.
return (...args: A) => {
11.
const now = Date.now();
12.
if (now - lastCall >= limit) {
13.
lastCall = now;
14.
fn(...args);
15.
}
16.
};
17.
}
18.
19.
export default throttle;

1. Installtion

npx @jrtilak/lazykit add throttle

2. Parameters

  • fn ((...args: A) => void)
    The function to be throttled. This function will be invoked at most once every limit milliseconds.

  • limit (number)
    The minimum time interval (in milliseconds) between invocations of fn.

3. Returns

  • (...args: A) => void
    Returns a new throttled function that, when called, will invoke fn at most once per every limit milliseconds.

4. Type Parameters

  • A
    The type of the arguments accepted by the function fn. This allows the throttled function to accept the same parameters as fn, ensuring type safety.

5. Usage

This example demonstrates how to use the throttle function with a text input field to control the frequency of function calls as the user types.

  • The normal value updates immediately as the user types in the input field.
  • The throttled value updates every 300 milliseconds, demonstrating how throttling limits the frequency of function execution.