Created
April 3, 2014 17:00
-
-
Save jeffreytgilbert/9958455 to your computer and use it in GitHub Desktop.
Example of sized queues, for things like, oh, i don't know, running limited numbers of selenium tests in parallel or downloading images two at a time or whatever.
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 runningProcessCount = 0, | |
processQueuePosition = 1, | |
processLimit = 2, | |
totalProcesses = 10; | |
function throttleProcesses(){ | |
if(processLimit > runningProcessCount){ | |
fakeProcess(); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
function fakeProcess(){ | |
var timeout = 1000 * (processQueuePosition); | |
console.log(processQueuePosition+' is currently running.'); | |
runningProcessCount++; | |
var thisProcessPosition = processQueuePosition; | |
processQueuePosition++; | |
setTimeout(function(){ | |
processFinished(thisProcessPosition); | |
},timeout); | |
} | |
function processFinished(processNumber){ | |
--runningProcessCount; | |
console.log(processNumber+' is finished being run.'); | |
if(processQueuePosition <= totalProcesses){ | |
throttleProcesses(); | |
} | |
} | |
while(processQueuePosition <= totalProcesses){ | |
console.log('starting '+processQueuePosition+' of '+totalProcesses); | |
if(!throttleProcesses()){ | |
break; // we hit the queue limit, so bounce from this init loop | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment