mirror of
https://github.com/bendtherules/JSQuestions.git
synced 2026-08-18 13:53:51 +00:00
53 lines
1.1 KiB
JavaScript
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; |