-
Notifications
You must be signed in to change notification settings - Fork 0
/
render-loop.ts
55 lines (46 loc) · 1.66 KB
/
render-loop.ts
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
export class RenderLoop {
private msLastFrame = performance.now();
private isActive = false;
private readonly msFpsLimit: number;
private readonly run: () => unknown;
private currentFps = 0;
public constructor(private readonly callback: (delta: number) => void, private readonly fps = 60) {
this.isActive = false;
this.msFpsLimit = 1000 / fps;
if (fps > 0) {
this.run = () => {
const msCurrent = performance.now();
const msDelta = (msCurrent - this.msLastFrame);
const deltaTime = msDelta / 1000.0;
if (msDelta >= this.msFpsLimit) {
this.currentFps = Math.floor(1 / deltaTime);
this.msLastFrame = msCurrent;
this.callback(deltaTime);
}
if (this.isActive) {
window.requestAnimationFrame(this.run);
}
};
} else {
this.run = () => {
const msCurrent = performance.now();
const deltaTime = (msCurrent - this.msLastFrame) / 1000.0;
this.currentFps = Math.floor(1 / deltaTime);
this.msLastFrame = msCurrent;
this.callback(deltaTime);
if (this.isActive) {
window.requestAnimationFrame(this.run);
}
};
}
}
public start(): this {
this.isActive = true;
this.msLastFrame = performance.now();
window.requestAnimationFrame(this.run);
return this;
}
public stop(): void {
this.isActive = false;
}
}