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 .catch(() => {}) .finally(() => { this.runningCount--; this._processQueue(); }); } } play(){ this.isProcessing = true; this._processQueue(); } pause(){ this.isProcessing = false; } } module.exports = TaskScheduler;