-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaskqueue.js
53 lines (45 loc) · 1.08 KB
/
taskqueue.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
// taskqueue.js
class TaskQueue {
constructor() {
this.queue = [];
this.isProcessing = false;
}
async addTask(task) {
return new Promise((resolve, reject) => {
this.queue.push({
task,
resolve,
reject
});
if (!this.isProcessing) {
this.processNext();
}
});
}
async processNext() {
if (this.queue.length === 0) {
this.isProcessing = false;
return;
}
this.isProcessing = true;
const { task, resolve, reject } = this.queue[0];
try {
const result = await task();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.queue.shift();
this.processNext();
}
}
clear() {
this.queue = [];
this.isProcessing = false;
}
get length() {
return this.queue.length;
}
}
// Create and export the instance
window.messageQueue = new TaskQueue();