forked from smfreegard/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 6
/
timer_queue.js
64 lines (49 loc) · 1.4 KB
/
timer_queue.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
"use strict";
function TQTimer (fire_time, cb) {
this.fire_time = fire_time;
this.cb = cb;
}
TQTimer.prototype.cancel = function () {
this.cb = null;
};
function TimerQueue (interval) {
var self = this;
interval = interval || 1000;
this.queue = [];
setInterval(function () { self.fire(); }, interval);
}
module.exports = TimerQueue;
TimerQueue.prototype.add = function (ms, cb) {
var fire_time = Date.now() + ms;
var timer = new TQTimer(fire_time, cb);
if ((this.queue.length === 0) ||
fire_time >= this.queue[this.queue.length - 1].fire_time) {
this.queue.push(timer);
return timer;
}
for (var i=0; i < this.queue.length; i++) {
if (this.queue[i].fire_time > fire_time) {
this.queue.splice(i, 0, timer);
return timer;
}
}
throw "Should never get here";
};
TimerQueue.prototype.fire = function () {
if (this.queue.length === 0) return;
var now = Date.now();
while (this.queue.length && this.queue[0].fire_time <= now) {
var to_run = this.queue.shift();
if (to_run.cb) to_run.cb();
}
};
TimerQueue.prototype.length = function () {
return this.queue.length;
};
TimerQueue.prototype.drain = function () {
if (this.queue.length === 0) return;
while (this.queue.length) {
var to_run = this.queue.shift();
if (to_run.cb) to_run.cb();
}
};