-
Notifications
You must be signed in to change notification settings - Fork 3
/
deferred-callback-queue.js
104 lines (92 loc) · 2.54 KB
/
deferred-callback-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
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
/**
* @author The TriSoft Team <[email protected]>
* @link https://www.trisoft.ro/
*/
function DeferredCallbackQueue(interval, autostart) {
this.queue = [];
this.interval = undefined;
this.start = function () {
if (this.interval !== undefined) {
clearInterval(this.interval);
}
this.interval = setInterval(this.work, interval || 100);
}.bind(this);
this.now = function () {
return (new Date()).getTime();
}.bind(this);
this.work = function () {
var now = this.now(), c, call;
for (c = 0; c < this.queue.length; c++) {
call = this.queue[c];
if (call.when < now) {
this.removeCall(call.func);
call.func();
}
}
}.bind(this);
this.stop = function () {
if (this.interval) {
clearInterval(this.interval);
delete this.interval;
}
}.bind(this);
this.addCall = function (func, delay) {
var now = this.now();
if (this.hasCall(func)) {
this.updateCall(func, now + delay);
return;
}
this.queue.push({
func: func,
delay: delay,
addedAt: now,
when: now + delay
});
}.bind(this);
this.updateCall = function (func, newWhen) {
var c;
for (c = 0; c < this.queue.length; c++) {
if (this.queue[c].func === func) {
this.queue[c].when = newWhen;
return;
}
}
}.bind(this);
this.removeCall = function (func) {
if (this.queue.length === 0) {
return;
}
var idx = -1, c;
for (c = 0; c < this.queue.length; c++) {
if (this.queue[c].func === func) {
idx = c;
break;
}
}
if (idx !== -1) {
this.queue = this
.queue
.slice(0, idx)
.concat(
this
.queue
.slice(idx + 1, this.queue.length - 1)
)
;
}
}.bind(this);
this.hasCall = function (func) {
return this.getCall(func) !== undefined;
}.bind(this);
this.getCall = function (func) {
var c;
for (c = 0; c < this.queue.length; c++) {
if (this.queue[c].func === func) {
return this.queue[c];
}
}
}.bind(this);
if (autostart === true) {
this.start();
}
}