-
Notifications
You must be signed in to change notification settings - Fork 3
/
kueue.js
99 lines (82 loc) · 2.29 KB
/
kueue.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
module.exports = function() {
var onSuccess,
running;
// holds the queue
var queue = [];
// log the current status
function status() {
console.log("Queue has " + queue.length + " items");
}
// event handler for status updates
this.onSuccess = function(handler) {
onSuccess = handler;
};
// add an item to the queue
this.add = function(id, action) {
// add the item to the queue
queue.push({
id: id,
attempts: 0,
action: action
});
status();
};
// get the queue status
this.status = function() {
return {
length: queue.length
};
};
// clear the queue
this.clear = function() {
queue = [];
};
// start the queue
this.start = function() {
console.log("Starting queue");
// set us to running
running = true;
function run() {
// only process if we're running
if (running) {
queue[0] && queue[0].action({
id: queue[0].id,
attempts: queue[0].attempts
}, function next() {
onSuccess({
id: queue[0].id,
length: queue.length - 1
});
queue.shift();
status();
if (running === true) {
run();
}
}, function retry() {
console.log("queue item failed -- retrying");
queue.push(queue[0]);
queue[0].attempts++;
queue.shift();
status();
if (running === true) {
run();
}
}, function cancel() {
console.log("cancelling queue item");
queue.shift();
status();
if (running === true) {
run();
}
})
}
}
run();
};
// stop the queue
this.stop = function() {
console.log("Stopping queue");
running = false;
};
return this;
};