-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
# 手写题目 | ||
|
||
JS 实现一个带并发限制的异步调度器 Scheduler | ||
|
||
题目描述 | ||
// JS 实现一个带并发限制的异步调度器 Scheduler | ||
// 保证同时运行的任务最多有两个 | ||
|
||
class Scheduler { | ||
constructor() { | ||
this._max = 2; | ||
} | ||
|
||
} | ||
|
||
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(2000, '1'); | ||
addTask(1000, '2'); | ||
addTask(3000, '3'); | ||
addTask(2000, '4'); | ||
|
||
2 第一秒 | ||
1 第二秒 | ||
3 第四秒 | ||
4 第四秒 |