I wrote this mini thread pool in JavaScript that takes a maximum number of concurrently running tasks and runs them in the order it was given. I appreciate any feedback or review. Thank you.
class TaskPool {
constructor(poolSize) {
this.poolSize = poolSize;
this.queue = [];
this.runningTasks = 0;
this.scheduled = null;
this.id = 0;
}
backgroundRunner() {
if (this.queue.length) {
if (this.runningTasks < this.poolSize) {
const index = 0;
const [[task, id]] = this.queue.splice(index, 1);
this.runningTasks++;
task(id).finally(() => {
this.runningTasks--;
this.backgroundRunner();
});
} else {
console.log('queue is full');
if (!this.scheduled) {
console.log('scheduled for later');
this.scheduled = setTimeout(() => {
this.backgroundRunner();
this.scheduled = false;
}, 1000);
}
}
}
}
run(task) {
this.queue.push([task, ++this.id]);
this.backgroundRunner();
}
}
Tests:
function task(id) {
//create an ID
return new Promise((resolve, _) => {
console.log('running task #', id);
setTimeout(() => {
console.log('done running task #', id);
resolve();
}, 400);
});
}
const pool = new TaskPool(3);
for (let i = 0; i < 10; i++) {
pool.run(task);
}