-
-
Save AnderRV/4299b933c2143eeffa36455eb618ff31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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