Skip to content

Instantly share code, notes, and snippets.

@AnderRV

AnderRV/index.js Secret

Last active August 31, 2021 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnderRV/4299b933c2143eeffa36455eb618ff31 to your computer and use it in GitHub Desktop.
Save AnderRV/4299b933c2143eeffa36455eb618ff31 to your computer and use it in GitHub Desktop.
const queue = (concurrency = 4) => {
let running = 0;
const tasks = [];
return {
enqueue: async (task, ...params) => {
tasks.push({ task, params }); // Add task to the list
if (running >= concurrency) {
return; // Do not run if we are above the concurrency limit
}
running += 1; // "Block" one concurrent task
while (tasks.length > 0) {
const { task, params } = tasks.shift(); // Take task from the list
await task(...params); // Execute task with the provided params
}
running -= 1; // Release a spot
},
};
};
// Just a helper function, Javascript has no sleep function
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const printer = async num => {
await sleep(2000);
console.log(num, Date.now());
};
const q = queue();
// Add 8 tasks that will sleep and print a number
for (let num = 0; num < 8; num++) {
q.enqueue(printer, num);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment