Skip to content

Instantly share code, notes, and snippets.

@ostgals
Last active October 10, 2015 18:06
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 ostgals/8c95160500350616cfff to your computer and use it in GitHub Desktop.
Save ostgals/8c95160500350616cfff to your computer and use it in GitHub Desktop.
Snippet - Multi-thread queue with jq's promises
{
// .....
enqueue: function(items, get_promise, num_threads){
num_threads = num_threads || 1;
var dfd = $.Deferred(), i = 0, num_total = items.length, num_active = 0, num_done = 0,
next = function(){
while (num_active < num_threads && i < num_total) {
num_active++;
get_promise(items[i++]).done(function(){
num_active--;
dfd.notify(++num_done, num_total);
if (num_done == num_total) dfd.resolve();
next();
});
});
};
next();
return dfd.promise();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment