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 everylimit
milliseconds. -
limit
(number
)
The minimum time interval (in milliseconds) between invocations offn
.
3. Returns
(...args: A) => void
Returns a new throttled function that, when called, will invokefn
at most once per everylimit
milliseconds.
4. Type Parameters
A
The type of the arguments accepted by the functionfn
. This allows the throttled function to accept the same parameters asfn
, 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.