-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
122 lines (93 loc) · 2.51 KB
/
index.js
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
// All common browsers limit the interval to 2^31 numbers.
// For this reason, we need some workarounds if we want to use intervals larger than that.
exports.maxInterval = Math.pow(2, 31) - 1;
function clamp(interval) {
return interval <= exports.maxInterval ? interval : exports.maxInterval;
}
function Timeout(cb, args, thisArg) {
this.timestamp = null;
this.timer = null;
this.cb = cb;
this.args = args;
this.thisArg = thisArg;
}
Timeout.fired = function (timeout) {
var now = Date.now();
if (timeout.timestamp > now) {
timeout.reschedule(timeout.timestamp - now);
} else {
timeout.fireNow();
}
};
Timeout.prototype.reschedule = function (interval) {
this.clear();
this.timer = setTimeout(Timeout.fired, clamp(interval), this);
};
Timeout.prototype.fireNow = function () {
this.clear();
this.cb.apply(this.thisArg, this.args);
};
Timeout.prototype.fireAt = function (timestamp) {
this.timestamp = timestamp;
this.reschedule(timestamp - Date.now());
};
Timeout.prototype.fireIn = function (interval) {
this.timestamp = Date.now() + interval;
this.reschedule(interval);
};
Timeout.prototype.clear = function () {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
};
function Interval(cb, args, thisArg) {
var that = this;
var callback = function () {
that.timeout.fireIn(that.interval);
cb.apply(that.timeout.thisArg, that.timeout.args);
};
this.timeout = new Timeout(callback, args, thisArg);
this.interval = null;
}
Interval.prototype.fireEvery = function (interval) {
this.interval = interval;
this.timeout.fireIn(interval);
};
Interval.prototype.clear = function () {
this.timeout.clear();
};
exports.Timeout = Timeout;
exports.Interval = Interval;
exports.setTimeoutAt = function (cb, timestamp) {
var args = [];
for (var i = 2; i < arguments.length; i += 1) {
args.push(arguments[i]);
}
var timer = new Timeout(cb, args, this);
timer.fireAt(timestamp);
return timer;
};
exports.setTimeout = function (cb, interval) {
var args = [];
for (var i = 2; i < arguments.length; i += 1) {
args.push(arguments[i]);
}
var timer = new Timeout(cb, args, this);
timer.fireIn(interval);
return timer;
};
exports.setInterval = function (cb, interval) {
var args = [];
for (var i = 2; i < arguments.length; i += 1) {
args.push(arguments[i]);
}
var timer = new Interval(cb, args, this);
timer.fireEvery(interval);
return timer;
};
exports.clearTimeout = exports.clearInterval = function (timer) {
if (timer && typeof timer.clear === 'function') {
timer.clear();
}
};