]> Untitled Git - lemmy-ui.git/blob - src/shared/utils/helpers/debounce.ts
Merge branch 'main' into breakout-role-utils
[lemmy-ui.git] / src / shared / utils / helpers / debounce.ts
1 export function debounce<T extends any[], R>(
2   func: (...e: T) => R,
3   wait = 1000,
4   immediate = false
5 ) {
6   let timeout: NodeJS.Timeout | null;
7
8   return function () {
9     const args = arguments;
10     const callNow = immediate && !timeout;
11
12     clearTimeout(timeout ?? undefined);
13
14     timeout = setTimeout(function () {
15       timeout = null;
16
17       if (!immediate) {
18         func.apply(this, args);
19       }
20     }, wait);
21
22     if (callNow) func.apply(this, args);
23   } as (...e: T) => R;
24 }