underbbs/frontend/ts/batch-timer.ts

26 lines
633 B
TypeScript
Raw Normal View History

export class BatchTimer {
private _batch: string[];
private _timer: number;
private _reqFn: (id: string[])=>void;
constructor(reqFn: (id: string[])=>void) {
this._batch = [];
this._timer = new Date().getTime();
this._reqFn = reqFn;
}
public queue(id: string, timeout: number){
if (!this._batch.includes(id)) {
this._timer = new Date().getTime() + timeout;
this._batch.push(id);
setTimeout(this.checkBatch.bind(this), timeout);
}
}
private checkBatch() {
if ((new Date()).getTime() >= this._timer) {
this._reqFn(this._batch);
this._batch = [];
}
}
}