-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.ts
44 lines (39 loc) · 1.11 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
//@ts-nocheck
/**
* Self-adjusting interval to account for drifting
*
* @param {function} workFunc Callback containing the work to be done
* for each interval
* @param {int} interval Interval speed (in milliseconds) - This
* @param {function} errorFunc (Optional) Callback to run if the drift
* exceeds interval
*/
export default function AdjustingInterval(workFunc, interval, errorFunc) {
const that = this;
let expected, timeout;
this.interval = interval;
this.start = function () {
expected = Date.now() + this.interval;
timeout = setTimeout(step, this.interval);
};
this.stop = function () {
clearTimeout(timeout);
};
function step() {
const drift = Date.now() - expected;
if (drift > that.interval) {
// You could have some default stuff here too...
if (errorFunc) errorFunc();
}
workFunc();
expected += that.interval;
timeout = setTimeout(step, Math.max(0, that.interval - drift));
}
}
class Timer {
interval: number;
#expected: number;
constructor() {
expected = Date.now();
}
}