Queuing/throttling jQuery ajax requests
ajax, javascript, jquery, jquery-deferred
Solution
The first thing you're stumbling upon is that `when()` doesn't work this way with arrays. It accepts an arbitrary list of promises so you can get around that by applying an array using:
$.when.apply(null, promiseList).done(function(){
// Do something
// use the `arguments` magic property to get an ordered list of results
});
Secondly, the throttling method can be done with $.ajax param of {delay:timeInSeconds} but I've proposed a solution that sets up a new defered which is immediately returned (to keep the order) but resolved after a timeout.
See http://jsfiddle.net/9Acb2/1/ for an interactive example
Problem
I need to fire a number of ajax requests at a server and then run a callback when they are finished. Normally this would be easy using jQuery's `deferred.done()` . However to avoid overwhelming the server, I'm queuing the requests, and firing one every X milliseconds. e.g ``` var promisesList = []; var addToQueue = function(workflow) { workflowQueue.push(workflow); } var startWorkflow = function(workflow) { return $.ajax($endointURL, { type: "POST", data: { action: workflow.id }, success: function() { }, error: function(jqXHR, textStatus, errorThrown) { } }); }; var startWorkflows = function() { var promisesList = []; if (workflowQueue.length > 0) { var workflow = workflowQueue.shift(); promisesList.push(startWorkflow(workflow)); setTimeout(startWorkflows, delay); } }; startWorkflows(); $.when(promisesList).done(function(){ //do stuff }); ``` The problem with this is, that the `promisesList` array is initially empty, so the `done()` callback fires immediately, and then the ajax requests start getting sent by the `setTimeout()`. Is there an easy way to create the ajax requests initially and kind of "pause" them, then fire them using `setTimeout()`. I've found various throttle/queue implementations to fire ajax requests sequentially, but I'm happy for them to be fired in parallel, just with a delay on them.