-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (58 loc) · 1.53 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
var _timer;
/**
* Singleton constructor for Timer
*
* @returns {Timer} Either new instance or existing instance of Timer
*/
var Timer = module.exports = function Timer() {
if(_timer) return _timer;
_timer = this;
this.time = 0;
this.intervals = {};
}
/**
* Advance time by 1 unit, and call appropriate intervals.
*
* TODO: Replace the naive loop with a priority queue
*
* @returns {Integer} new time
*/
Timer.prototype.tick = function Timer$tick() {
this.time++;
var i;
Object.keys(this.intervals).forEach(function(id) {
i = this.intervals[id];
if((this.time - i.offset) % i.delay === 0)
i.callback.call(null, (this.time - i.offset) / i.delay);
}.bind(this));
return this.time;
}
/**
* Add a new interval to the timer. Opposed the the default Javascript
* setInterval, this takes the delay first and then the callback.
*
* @param {Integer} time delay between calls
* @param {Function} callback
*
* @returns {Integer} id of the interval. This is used the clear the interval
*/
Timer.prototype.setInterval = function Timer$setInterval(delay, callback) {
var id = Object.keys(this.intervals).length;
this.intervals[id] = {
offset: this.time,
delay: delay,
callback: callback
};
return id;
}
/**
* Removes the interval from the timer
*
* @param {Integer|String} id of the interval
*
* @returns {Timer} for chaining
*/
Timer.prototype.clearInterval = function Timer$clearInterval(id) {
delete this.intervals[id];
return this;
}