-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0-test.js
49 lines (44 loc) · 800 Bytes
/
0-test.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
class Scheduler {
constructor() {
this.queue = []
this.maxCount = 2
this.runCounts = 0
}
add(promiseCreator) {
this.queue.push(promiseCreator)
}
taskStart() {
for (let i = 0; i < this.maxCount; i++) {
this.request()
}
}
request() {
if (!this.queue || !this.queue.length || this.runCounts >= this.maxCount) {
return
}
this.runCounts++
this.queue
.shift()()
.then(() => {
this.runCounts--
this.request()
})
}
}
const timeout = time =>
new Promise(resolve => {
setTimeout(resolve, time)
})
const scheduler = new Scheduler()
const addTask = (time, order) => {
scheduler.add(() => timeout(time).then(() => console.log(order)))
}
addTask(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(400, '4')
scheduler.taskStart()
// 2
// 3
// 1
// 4