编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
function Scheduler(limit) {
    this.stack = []
    this.count = 0
    this.limit = limit // 并发最大数量
}
Scheduler.prototype.add = function(time, fn) {
    // 调度器增加任务
    const task = () => {
        return new Promise((resolve, reject)=> {
            setTimeout(() => {
                fn()
                resolve()
            }, time)
        })
    }
    this.stack.push(task)
}
Scheduler.prototype.taskStart = function() {
    // 执行调度器 - 根据limit进行限制
    for(let i = 0; i < this.limit; i++) {
        this.request()
    }
}
Scheduler.prototype.request = function() {
    // 执行异步任务
    if(!this.stack.length || this.count >= this.limit) {
        return;
    }
    this.count++
    let task = this.stack.shift()
    task().then((res) => {
        this.count--
        this.request()
    })
}

let addTask = new Scheduler(2)
addTask.add(1000,() => { console.log('1') });
addTask.add(500,() => { console.log('2') });
addTask.add(300,() => { console.log('3') });
addTask.add(400,() => { console.log('4') });
addTask.taskStart()