fix throttle function not being able to run with argument(s)

This commit is contained in:
undergroundwires
2021-03-13 12:14:44 +01:00
parent 1f515e7be5
commit 1935db1019
2 changed files with 108 additions and 24 deletions

View File

@@ -1,20 +1,10 @@
export function throttle<T extends []>(
callback: (..._: T) => void, wait: number,
timer: ITimer = NodeTimer): (..._: T) => void {
let queuedToRun: ReturnType<typeof setTimeout>;
let previouslyRun: number;
return function invokeFn(...args: T) {
const now = timer.dateNow();
if (queuedToRun) {
queuedToRun = timer.clearTimeout(queuedToRun) as undefined;
}
if (!previouslyRun || (now - previouslyRun >= wait)) {
callback(...args);
previouslyRun = now;
} else {
queuedToRun = timer.setTimeout(invokeFn.bind(null, ...args), wait - (now - previouslyRun));
}
};
export type CallbackType = (..._: any[]) => void;
export function throttle(
callback: CallbackType, waitInMs: number,
timer: ITimer = NodeTimer): CallbackType {
const throttler = new Throttler(timer, waitInMs, callback);
return (...args: any[]) => throttler.invoke(...args);
}
export interface ITimer {
@@ -28,3 +18,35 @@ const NodeTimer: ITimer = {
clearTimeout: (timeoutId) => clearTimeout(timeoutId),
dateNow: () => Date.now(),
};
interface IThrottler {
invoke: CallbackType;
}
class Throttler implements IThrottler {
private queuedToRun: ReturnType<typeof setTimeout>;
private previouslyRun: number;
constructor(
private readonly timer: ITimer,
private readonly waitInMs: number,
private readonly callback: CallbackType) {
if (!timer) { throw new Error('undefined timer'); }
if (!waitInMs) { throw new Error('no delay to throttle'); }
if (waitInMs < 0) { throw new Error('negative delay'); }
if (!callback) { throw new Error('undefined callback'); }
}
public invoke(...args: any[]): void {
const now = this.timer.dateNow();
if (this.queuedToRun) {
this.queuedToRun = this.timer.clearTimeout(this.queuedToRun) as undefined;
}
if (!this.previouslyRun || (now - this.previouslyRun >= this.waitInMs)) {
this.callback(...args);
this.previouslyRun = now;
} else {
const nextCall = () => this.invoke(...args);
const nextCallDelayInMs = this.waitInMs - (now - this.previouslyRun);
this.queuedToRun = this.timer.setTimeout(nextCall, nextCallDelayInMs);
}
}
}