Skip to content

Instantly share code, notes, and snippets.

@jackyef
Created April 28, 2021 05:20
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 jackyef/817bc700e894a71daaa74470fed80a5e to your computer and use it in GitHub Desktop.
Save jackyef/817bc700e894a71daaa74470fed80a5e to your computer and use it in GitHub Desktop.
const serialCon = (timeArray, maxConcurrency) => {
let activePromiseCount = 0
const times = [...timeArray]
const processNextPromise = () => {
const time = times.shift()
if (!time) return
const newPromise = new Promise((resolve) =>
setTimeout(() => {
console.log(time)
resolve()
}, time)
)
activePromiseCount += 1
// Finished processed one promise
// Now we can process another one!
newPromise.then(() => {
activePromiseCount -= 1
processNextPromise()
})
// Maximum concurrency not reached yet, let's process another one
if (activePromiseCount < maxConcurrency) {
processNextPromise()
}
}
// Start the recursive calls off!
processNextPromise()
}
const timeoutArray = [1000, 100, 200, 300, 400, 500]
// serialCon(timeoutArray, 1)
serialCon(timeoutArray, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment