编辑代码

class TaskScheduler {
    constructor() {
        this.max = 2;  // Maximum number of concurrent tasks
        this.cur = 0;  // Number of tasks currently running
        this.list = [];  // Task queue
    }

    run() {
        if (this.cur < this.max && this.list.length > 0) {
            this.cur++;  // Increment current running tasks count
            const task = this.list.shift();  // Take the next task
            task().finally(() => {
                this.cur--;  // Decrement the task count after it completes
                this.run();  // Continue with the next task in the queue
            });
        }
    }

    addTask(fn) {
        this.list.push(fn);  // Add task to the queue
        this.run();  // Start running tasks
    }
}

// Helper function to simulate a promise-based timeout task
function promiseTimeout(time, label) {
    return () => new Promise((resolve) => {
        console.time(label);  // Start timing
        setTimeout(() => {
            resolve();
            
        }, time);
    }).then(()=>console.timeEnd(label)) // End timing when resolved)
    ;
}

// Example usage
let scheduler = new TaskScheduler();

scheduler.addTask(promiseTimeout(1000, "1"));
scheduler.addTask(promiseTimeout(2000, "2"));
scheduler.addTask(promiseTimeout(3000, "3"));
scheduler.addTask(promiseTimeout(4000, "4"));