summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/streaming/render_balancer.js
blob: 66929ff3a54ad422db6e0478cc238f47e5eb7e15 (plain)
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
27
28
29
30
31
32
33
34
35
36
export class RenderBalancer {
  previousTimestamp = undefined;

  constructor({ increase, decrease, highFrameTime, lowFrameTime }) {
    this.increase = increase;
    this.decrease = decrease;
    this.highFrameTime = highFrameTime;
    this.lowFrameTime = lowFrameTime;
  }

  render(fn) {
    return new Promise((resolve) => {
      const callback = (timestamp) => {
        this.throttle(timestamp);
        if (fn()) requestAnimationFrame(callback);
        else resolve();
      };
      requestAnimationFrame(callback);
    });
  }

  throttle(timestamp) {
    const { previousTimestamp } = this;
    this.previousTimestamp = timestamp;
    if (previousTimestamp === undefined) return;

    const duration = Math.round(timestamp - previousTimestamp);
    if (!duration) return;

    if (duration >= this.highFrameTime) {
      this.decrease();
    } else if (duration < this.lowFrameTime) {
      this.increase();
    }
  }
}