index.js
2.11 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
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
var TIMEOUT_MAX = 2147483647; // 2^31-1
exports.setTimeout = function(listener, after) {
return new Timeout(listener, after)
}
exports.setInterval = function(listener, after) {
return new Interval(listener, after)
}
exports.clearTimeout = function(timer) {
if (timer) timer.close()
}
exports.clearInterval = exports.clearTimeout
exports.Timeout = Timeout
exports.Interval = Interval
function Timeout(listener, after) {
this.listener = listener
this.after = after
this.unreffed = false
this.start()
}
Timeout.prototype.unref = function() {
if (!this.unreffed) {
this.unreffed = true
this.timeout.unref()
}
}
Timeout.prototype.ref = function() {
if (this.unreffed) {
this.unreffed = false
this.timeout.ref()
}
}
Timeout.prototype.start = function() {
if (this.after <= TIMEOUT_MAX) {
this.timeout = setTimeout(this.listener, this.after)
} else {
var self = this
this.timeout = setTimeout(function() {
self.after -= TIMEOUT_MAX
self.start()
}, TIMEOUT_MAX)
}
if (this.unreffed) {
this.timeout.unref()
}
}
Timeout.prototype.close = function() {
clearTimeout(this.timeout)
}
function Interval(listener, after) {
this.listener = listener
this.after = this.timeLeft = after
this.unreffed = false
this.start()
}
Interval.prototype.unref = function() {
if (!this.unreffed) {
this.unreffed = true
this.timeout.unref()
}
}
Interval.prototype.ref = function() {
if (this.unreffed) {
this.unreffed = false
this.timeout.ref()
}
}
Interval.prototype.start = function() {
var self = this
if (this.timeLeft <= TIMEOUT_MAX) {
this.timeout = setTimeout(function() {
self.listener()
self.timeLeft = self.after
self.start()
}, this.timeLeft)
} else {
this.timeout = setTimeout(function() {
self.timeLeft -= TIMEOUT_MAX
self.start()
}, TIMEOUT_MAX)
}
if (this.unreffed) {
this.timeout.unref()
}
}
Interval.prototype.close = function() {
Timeout.prototype.close.apply(this, arguments)
}