decounce

Returns 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.
/**
2.
* Returns a debounced function that delays invoking the passed function until after `given` milliseconds have elapsed since the last time the debounced function was invoked.
3.
**/
4.
5.
function debounce<A extends unknown[]>(
6.
fn: (...args: A) => void,
7.
delay: number = 300,
8.
) {
9.
let timer: any;
10.
return (...args: A) => {
11.
clearTimeout(timer);
12.
timer = setTimeout(() => {
13.
fn(...args);
14.
}, delay);
15.
};
16.
}
17.
18.
export default debounce;

1. Installtion

npx @jrtilak/lazykit add debounce

2. Parameters

  • fn ((...args: A) => void)
    The function to debounce. This function will be invoked after the specified delay.

  • delay (optional) (number)
    The number of milliseconds to wait before invoking fn after the last call to the debounced function. Defaults to 300.

3. Returns

  • (...args: A) => void
    Returns a new debounced function that, when called, will delay the invocation of fn until after the specified delay has elapsed since the last time the debounced function was invoked.

4. Type Parameters

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

5. Usage

This example effectively illustrates how debounce can help optimize user input handling in web applications by reducing the number of updates that occur in quick succession, resulting in a smoother experience.