-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.ts
131 lines (101 loc) · 2.3 KB
/
timer.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/**
* Created by user on 2017/11/10/010.
*/
import * as moment from 'moment';
import { QueueTimer, ICallback, ITimeQueueItem, ITimeQueueItemAdd, ITimeData } from './queue.timer';
import { autobind, readonly, nonconfigurable, coreDecorators } from './lib/decorators';
export interface ITimerFunc extends Function
{
(callback: ICallback, delay: number, ...params);
(callback: ICallback, delay: moment.Duration, ...params);
}
export interface ITimer
{
setTimeout: ITimerFunc;
setInterval: ITimerFunc;
setImmediate(callback: ICallback, ...params);
}
@autobind
export class Timer implements ITimer
{
public timer: QueueTimer;
public cache = {
done: [] as ITimeQueueItem[],
};
constructor(options?: ITimeData)
{
this.timer = QueueTimer.new(options);
}
async setTimeout(callback: ICallback, delay: number | moment.Duration, ...params)
{
let q = this.timer.add({
callback: callback,
timing: moment.duration(delay),
params: params,
type: 'setTimeout',
});
return q;
}
async setInterval(callback: ICallback, delay: number | moment.Duration, ...params)
{
let q = this.timer.add({
callback: callback,
timing: moment.duration(delay),
params: params,
type: 'setInterval',
});
return q;
}
async setImmediate(callback: ICallback, ...params)
{
let q = this.timer.add({
callback: callback,
timing: moment.duration(0),
params: params,
type: 'setImmediate',
});
return q;
}
async start(amount?: number | moment.Duration)
{
if (amount < 0)
{
amount = this.timer.cache.min;
}
await this.timer.update(amount);
await this.timer.sort();
if (this.timer.hasExpires())
{
await this.run();
}
return this;
}
async run()
{
let now = this.timer.now();
this.cache.done = [];
for (let idx in this.timer.queue)
{
let current = this.timer.queue[idx];
if (now.diff(current.timing) >= 0)
{
current.active = moment();
await current.callback(current, this.timer);
this.timer.remove(idx);
current.ending = moment();
this.cache.done.push(current);
}
else
{
break;
}
}
this.timer._cache_refresh();
return this;
}
}
export const init = new Timer();
export default init;
export const setTimeout = init.setTimeout;
export const setInterval = init.setInterval;
export const setImmediate = init.setImmediate;