Skip to content

Commit e229d61

Browse files
Apply throttle changes
1 parent e9fe93d commit e229d61

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

apps/webapp/app/utils/throttle.ts

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
1-
//From: https://kettanaito.com/blog/debounce-vs-throttle
2-
3-
/** A very simple throttle. Will execute the function at the end of each period and discard any other calls during that period. */
1+
/** A throttle that fires the first call immediately and ensures the last call during the duration is also fired. */
42
export function throttle(
53
func: (...args: any[]) => void,
64
durationMs: number
75
): (...args: any[]) => void {
8-
let isPrimedToFire = false;
9-
10-
return (...args: any[]) => {
11-
if (!isPrimedToFire) {
12-
isPrimedToFire = true;
6+
let timeoutId: NodeJS.Timeout | null = null;
7+
let nextArgs: any[] | null = null;
138

14-
setTimeout(() => {
15-
func(...args);
16-
isPrimedToFire = false;
17-
}, durationMs);
9+
const wrapped = (...args: any[]) => {
10+
if (timeoutId) {
11+
nextArgs = args;
12+
return;
1813
}
14+
15+
func(...args);
16+
17+
timeoutId = setTimeout(() => {
18+
timeoutId = null;
19+
if (nextArgs) {
20+
const argsToUse = nextArgs;
21+
nextArgs = null;
22+
wrapped(...argsToUse);
23+
}
24+
}, durationMs);
1925
};
26+
27+
return wrapped;
2028
}

0 commit comments

Comments
 (0)