Created
August 24, 2017 05:54
-
-
Save fukajun/007f4f1244cd7d89c8a827fa8e1b2dd2 to your computer and use it in GitHub Desktop.
Limit concurency count on javascript
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
var list = [] | |
for(i = 0; i < 200; i++) { | |
list.push(i) | |
} | |
var semaphore = [true, true, true, true, true, true] | |
var uploadImage = function(num, callback) { | |
setTimeout(function() { | |
console.log('upload', num) | |
callback() | |
}, 2000) | |
} | |
var startWorker = function() { | |
var timerId = setInterval(function() { | |
if(list.length <= 0) { | |
console.log('end') | |
clearInterval(timerId) | |
return; | |
} | |
if(semaphore.length >= 1) { | |
semaphore.shift() | |
var num = list.shift() | |
uploadImage(num, function() { | |
semaphore.push(true) | |
}) | |
} else { | |
console.log('waiting....') | |
} | |
}, 1000) | |
} | |
for(i in semaphore) { | |
startWorker(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment