Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created September 20, 2012 14:16
Show Gist options
  • Save threepointone/3756209 to your computer and use it in GitHub Desktop.
Save threepointone/3756209 to your computer and use it in GitHub Desktop.
Simple Queue/Parallel exec in js
var q = function() {
var args = _.flatten(arguments);
var ctr = args.length;
var complete;
function run(i) {
args[i](function() {
if (i + 1 === ctr) {
if (complete) {
complete();
}
} else {
run(i + 1);
}
});
}
run(0);
return ({
then: function(fn) {
complete = fn;
}
});
};
var parallel = function() {
var args = _.flatten(arguments);
var ctr = args.length;
var complete;
_.each(args, function(f) {
f(function() {
ctr--;
if (ctr === 0) {
if (complete) {
complete();
}
}
});
});
return ({
then: function(fn) {
complete = fn;
}
});
};
@threepointone
Copy link
Author

q(function(done){
    setTimeout(function(){
        done();
    },3000);
}, function(done){
    setTimeout(function(){
        done();
    },5000);
} /* ,add more functions in the queue array */ ).then(function(){
    console.log('finished!')
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment