throttle

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

1. Code

function throttle<A extends any[]>(
  fn: (...args: A) => void,
  limit: number
): (...args: A) => void {
  let lastCall = 0;
  return (...args: A) => {
    const now = Date.now();
    if (now - lastCall >= limit) {
      lastCall = now;
      fn(...args);
    }
  };
}

export default throttle;

2. Installation

npx @jrtilak/lazykit@latest add throttle

3. Description

The throttle function returns a new function that will only invoke the passed function at most once per every given milliseconds. It is useful for limiting the rate at which a function is invoked.

4. Props

Prop

Type

Default Value

function*Function---
limit*number300

5. Examples

import throttle from ".";

const log = throttle((message: string) => {
  console.log(message);
}, 2000);

log("Hello"); // Will print 'Hello'
log("Hello again"); // Will be ignored if called within 2 seconds from the first call

setTimeout(() => log("Hello after 2 seconds"), 2100); // Will print 'Hello after 2 seconds'