Skip to content

Instantly share code, notes, and snippets.

@rasjonell
Last active December 1, 2022 14:29
Show Gist options
  • Save rasjonell/e96c0119eaba1aa47a2cc7eaa810f5e5 to your computer and use it in GitHub Desktop.
Save rasjonell/e96c0119eaba1aa47a2cc7eaa810f5e5 to your computer and use it in GitHub Desktop.
Event Loop-like Task Runner with a limit on concurrently running processes
class TaskRunner {
constructor(concurrencyLimit) {
this.count = 0;
this.queue = [];
this.concurrent = concurrencyLimit;
}
add(task) {
const microTask = async () => {
await task();
this.count--;
this._run();
}
this.queue.push(microTask);
this._run();
}
_run() {
if (this.count < this.concurrent) {
this.count++;
if (this.queue.length > 0) {
const task = this.queue.shift();
queueMicrotask(task);
}
}
}
}
function task(x) {
return function() {
return new Promise((resolve, _) => {
setTimeout(() => {
console.log('task completed', x);
resolve();
}, 1000);
})
}
}
const taskRunner = new TaskRunner(3);
// The Task Runner will run these three tasks concurrently.
taskRunner.add(task(1));
taskRunner.add(task(2));
taskRunner.add(task(3));
// After those are done, it will porceed to complete theese three.
taskRunner.add(task(4));
taskRunner.add(task(5));
taskRunner.add(task(6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment