-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.js
69 lines (60 loc) · 1.05 KB
/
2.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
const urls = [
{
info: "link1",
time: 2000,
},
{
info: "link2",
time: 3000,
},
{
info: "link3",
time: 3000,
},
{
info: "link4",
time: 5000,
},
];
function loadImg(url) {
return new Promise((resolve, reject) => {
console.log("--", url.info + "start");
setTimeout(() => {
console.log("--", url.info + "end");
resolve();
}, url.time);
});
}
class Scheduler {
constructor(n) {
this.max = n || 2;
this.currentCount = 0;
this.taskQueue = []; // 当前执行任务队列
}
add(task) {
this.taskQueue.push(task);
this.run();
}
run() {
if (this.taskQueue.length === 0 || this.currentCount >= this.max) {
return;
}
this.currentCount++;
const fn = this.taskQueue.shift();
fn()
.then(() => {
this._next();
})
.catch(() => {
this._next();
});
}
_next() {
this.currentCount--;
this.run();
}
}
const scheduler = new Scheduler();
urls.forEach((url) => {
scheduler.add(() => loadImg(url));
});