-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtimers.js
65 lines (42 loc) · 1.49 KB
/
timers.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
// Timers() class is used to wrap setTimeout/clearTimeout by keeping timers in an object.
// That allows, for example, to clear all the timers simultaneously, avoiding "timer leaks".
function Timers() {
this.timers = {};
this.idCounter = 0;
}
// Use `id` for those timeouts which you want to stop manually, e.g. for those which iterate themselves.
Timers.prototype.setTimeout = function (id, callback, delay, triggerBeforeClear) {
var self = this;
// ID can be provided by the user.
if (typeof id == 'function') {
triggerBeforeClear = delay;
delay = callback;
callback = id;
id = self.idCounter++;
} else {
self.clearTimeout(self.timers[id]);
}
self.timers[id] = {
timerID: setTimeout(function () {
callback();
delete self.timers[id];
}, delay),
triggerBeforeClear: triggerBeforeClear, // If set to true, `callback` will be invoked just before clearing.
callback: callback
};
return id;
};
Timers.prototype.clearTimeout = function (id) {
var self = this,
timer = self.timers[id];
if (!timer) return;
if (timer.triggerBeforeClear) timer.callback(); // That is used to immediately stop oscillators.
clearTimeout(timer.timerID);
delete self.timers[id];
};
Timers.prototype.nullifyTimers = function () {
var self = this;
Object.keys(self.timers).forEach(self.clearTimeout.bind(self));
self.timers = {};
self.idCounter = 0;
};