all repos — underbbs @ 7a2eb99eb6d60d23c034f6255d5b52aea08e24d5

decentralized social media client

frontend/ts/batch-timer.ts (raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 = [];
    }
  }
}