classTaskScheduler{
constructor() {
this.max = 2; // Maximum number of concurrent tasksthis.cur = 0; // Number of tasks currently runningthis.list = []; // Task queue
}
run() {
if (this.cur < this.max && this.list.length > 0) {
this.cur++; // Increment current running tasks countconst task = this.list.shift(); // Take the next task
task().finally(() => {
this.cur--; // Decrement the task count after it completesthis.run(); // Continue with the next task in the queue
});
}
}
addTask(fn) {
this.list.push(fn); // Add task to the queuethis.run(); // Start running tasks
}
}
// Helper function to simulate a promise-based timeout taskfunctionpromiseTimeout(time, label) {
return() =>newPromise((resolve) => {
console.time(label); // Start timingsetTimeout(() => {
resolve();
}, time);
}).then(()=>console.timeEnd(label)) // End timing when resolved)
;
}
// Example usagelet scheduler = new TaskScheduler();
scheduler.addTask(promiseTimeout(1000, "1"));
scheduler.addTask(promiseTimeout(2000, "2"));
scheduler.addTask(promiseTimeout(3000, "3"));
scheduler.addTask(promiseTimeout(4000, "4"));