Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Last active August 12, 2024 16:17
Show Gist options
  • Save satyam4p/4b247886a35cf4d0491ebe09c032f785 to your computer and use it in GitHub Desktop.
Save satyam4p/4b247886a35cf4d0491ebe09c032f785 to your computer and use it in GitHub Desktop.
Taskqueue with given concurrency
class AsyncTaskQueue {
constructor(concurrency) {
this.concurrency = concurrency;
this.running = 0;
this.queue = [];
}
pushtask(task) {
this.queue.push(task);
process.nextTick(this.next.bind(this));
return this;
}
next() {
while (this.running < this.concurrency && this.queue.length) {
const task = this.queue.shift();
task(() => {
this.running--;
process.nextTick(this.next.bind(this));
});
this.running++;
}
}
}
function makeSimpleTask(name) {
return (cb) => {
console.log("started", name);
setTimeout(() => {
console.log(name, "completed");
cb();
}, Math.random() * 2000);
};
}
const taskQueue = new AsyncTaskQueue(3);
taskQueue.pushtask(makeSimpleTask("task 1"));
taskQueue.pushtask(makeSimpleTask("task 2"));
taskQueue.pushtask(makeSimpleTask("task 3"));
taskQueue.pushtask(makeSimpleTask("task 4"));
taskQueue.pushtask(makeSimpleTask("task 5"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment