-
Notifications
You must be signed in to change notification settings - Fork 0
/
clock.ts
51 lines (40 loc) · 1.08 KB
/
clock.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
const now = () => (typeof performance === "undefined" ? Date : performance).now();
export class Clock {
private startTime = 0;
private oldTime = 0;
private elapsedTime = 0;
private running = false;
public constructor(
private autostart = true,
) {
}
public start(): void {
this.startTime = now();
this.oldTime = this.startTime;
this.elapsedTime = 0;
this.running = true;
}
public stop(): void {
this.getElapsedTime();
this.running = false;
this.autostart = false;
}
public getElapsedTime(): number {
this.getDelta();
return this.elapsedTime;
}
public getDelta(): number {
let diff = 0;
if (this.autostart && !this.running) {
this.start();
return 0;
}
if (this.running) {
const newTime = now();
diff = (newTime - this.oldTime) / 1000;
this.oldTime = newTime;
this.elapsedTime += diff;
}
return diff;
}
}