-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
61 lines (48 loc) · 1.09 KB
/
index.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
56
57
58
59
60
61
export class Timer {
private _minutes: number = 0;
private _seconds: number = 0;
private startTime: number = 0;
private endTime: number = 0;
private interval: NodeJS.Timeout = null;
minutes(minutes: number) {
this._minutes = minutes;
return this;
}
seconds(seconds: number) {
this._seconds = seconds;
return this;
}
async sync() {
await new Promise(resolve => this.listen(resolve));
}
listen(cb: CallableFunction = null) {
if (!cb) {
return;
}
this.interval = setInterval(() => {
if (this.isExpired()) {
this.stop();
cb();
}
}, 1000);
}
stop() {
if (this.interval) {
clearInterval(this.interval);
}
}
start() {
let length = this._minutes * 60 + this._seconds;
this.startTime = ~~(Date.now() / 1000);
this.endTime = this.startTime + length;
return this;
}
update() {
let length: number = this._minutes * 60 + this._seconds;
this.endTime = this.startTime + length;
}
isExpired() {
let now = ~~(Date.now() / 1000);
return now >= this.endTime;
}
}