-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.js
More file actions
43 lines (34 loc) · 1.02 KB
/
timer.js
File metadata and controls
43 lines (34 loc) · 1.02 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
module.exports = Timer;
// Timer is a class that can be used to scheduled timeouts
// it is initialized with a timeout expressed in milliseconds, from the time of the call
function Timer(milliseconds)
{
var self;
self = this;
this.promise = new Promise(function(fulfill, reject) {
self.reject = reject;
self.timeout = setTimeout(function() {
fulfill(true);
}, milliseconds);
});
}
// wait returns a promise that resolves when the timeout has elapsed
Timer.prototype.wait = function()
{
return this.promise;
};
// cancel cancels a timeout. the promise will reject if the timeout hasn't elapsed yet
Timer.prototype.cancel = function()
{
this.reject("timeout canceled");
};
// defer is a static method that returns a promise that asynchronously fulfills after
// the event loop has processed pending IO requests.
Timer.defer = function()
{
return new Promise (function(fulfill, reject) {
setImmediate(function() {
fulfill(true);
});
});
}