Skip to content

Instantly share code, notes, and snippets.

@jeffreytgilbert
Created April 3, 2014 17:00
Show Gist options
  • Save jeffreytgilbert/9958455 to your computer and use it in GitHub Desktop.
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.
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