Skip to content

Commit

Permalink
fix: correct throttle logic
Browse files Browse the repository at this point in the history
  • Loading branch information
KazariEX committed Oct 9, 2024
1 parent ca15618 commit ec8b850
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
export function throttle<T extends unknown[]>(func: (...args: T) => void, delay: number) {
let start: number;
let start = 0;
let timer: NodeJS.Timeout | undefined = void 0;
return function(this: unknown, ...args: T) {
if (!timer) {
start = performance.now();
func.apply(this, args);
if (timer) {
clearTimeout(timer);
timer = void 0;
}
clearTimeout(timer);
timer = setTimeout(() => {
const now = performance.now() / 1000;
if (!start || now - start >= delay) {
func.apply(this, args);
timer = void 0;
}, delay - (performance.now() - start) / 1000);
start = now;
}
else {
timer = setTimeout(() => {
func.apply(this, args);
start = performance.now();
timer = void 0;
}, delay + start - now);
}
};
}

Expand Down

0 comments on commit ec8b850

Please sign in to comment.