题目
要求限制并发数量为2,按照次序和时间顺序执行
class Scheduler {
add(promiseCreater) {}
}
const timeout = (time) => new Promise(resolve => {
setTimeout(resolve, time);
})
const scheduler = new Scheduler();
const addTask = (time, order) => {
scheduler.add(() => timeout(time).then(() => consle.log(order)))
}
addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');
// 要求 output 2 3 1 4
参考答案
class Scheduler {
list = [];
maxLength = 2;
current = 0;
constructor() {
}
add(promiseCreater) {
this.list.push(promiseCreater);
this.start();
}
start() {
if (this.current < this.maxLength) {
if (!this.list[this.current]) return;
this.list[this.current]().t