-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimer.js
More file actions
66 lines (57 loc) · 1.56 KB
/
Timer.js
File metadata and controls
66 lines (57 loc) · 1.56 KB
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
'use strict';
const tools = require("./toolbox");
const MAX_TIMEOUT = 0x7FFFFFFF;
/**
* Implements a reprogrammable timer that is immune to the duration limitation in the standard API.
*/
class Timer {
/**
* Builds a timer that executes the <code>func</code> function when triggered.
* @param {function} func the function to execute, without passing any arguments
* @param {boolean} persistent indicates that this object should keep the event loop alive if it has
* work to do in future
*/
constructor(func, persistent) {
tools.mustBeFunction(func);
this.func = () => {
this.timer = null;
this.triggerTime = null;
func();
};
this.triggerTime = null;
this.timer = null;
this.unref = !persistent; // implicit conversion to boolean
}
/**
* Triggers the timer at the specified <code>time</code>, in milliseconds from the UNIX epoch time.
*/
trigger(time) {
tools.mustBeNumber(time, true);
if (time === this.triggerTime)
return; // no actual change
this.triggerTime = time;
if (this.timer)
this.timer.clearTimeout();
const schedule = () => {
// (re)compute the delay
const delay = time - Date.now();
if (delay < 1)
return process.nextTick(this.func); // it's already late
this.timer = delay > MAX_TIMEOUT ? setTimeout(schedule, MAX_TIMEOUT) : setTimeout(this.func, delay);
if (this.unref)
this.timer.unref();
};
schedule();
}
/**
* Cancels the timer.
*/
cancel() {
this.triggerTime = null;
if (this.timer) {
this.timer.clearTimeout();
this.timer = null;
}
}
}
module.exports = Timer;