debounce

Return a debounced function that delays invoking the passed function until after `given` milliseconds have elapsed since the last time the debounced function was invoked.

1. Code

function debounce<A extends any[]>(
  fn: (...args: A) => void,
  delay: number = 300
) {
  let timer: any;
  return (...args: A) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}

export default debounce;

2. Installation

npx @jrtilak/lazykit@latest add debounce

3. Description

The debounce function returns a new function that will only invoke the passed function after given milliseconds have elapsed since the last time the debounced function was invoked.

4. Props

Prop

Type

Default Value

function*Function---
delay*number300

5. Examples

import debounce from ".";

const handleButtonClick = () => {
  console.log("Button Clicked");
};

const debouncedHandleButtonClick = debounce(handleButtonClick);

debouncedHandleButtonClick();

// this will prevent a user clicking a button repeatedly giving some delay between each funtion call
debouncedHandleButtonClick();
debouncedHandleButtonClick();