Files
JSQuestions/solutions/async-scheduler.js
T
2026-02-06 13:52:15 +05:30

53 lines
1.1 KiB
JavaScript

class TaskScheduler {
constructor(concurrency = 1) {
this.queue = [];
this.isProcessing = false;
this.concurrencyLimit = concurrency;
this.runningCount = 0;
}
addTask(taskFn) {
const { promise, resolve, reject } = Promise.withResolvers();
this.queue.push({
taskFn,
resolve,
reject,
});
this._processQueue();
return promise;
}
_processQueue() {
if (!this.isProcessing) return;
while (this.runningCount < this.concurrencyLimit && this.queue.length > 0) {
const {
taskFn,
resolve,
reject,
} = this.queue.shift();
this.runningCount++;
// Ensure taskFn errors are captured as rejections
const taskPromise = Promise.resolve().then(() => taskFn());
taskPromise.then(resolve, reject);
taskPromise.finally(() => {
this.runningCount--;
this._processQueue();
});
}
}
play(){
this.isProcessing = true;
this._processQueue();
}
pause(){
this.isProcessing = false;
}
}
module.exports = TaskScheduler;