Skip to content

Instantly share code, notes, and snippets.

@triple-j
Created November 27, 2013 15:12
Show Gist options
  • Save triple-j/7677307 to your computer and use it in GitHub Desktop.
Save triple-j/7677307 to your computer and use it in GitHub Desktop.
Run a bunch of ajax requests linearly. Each request may have unique ajax settings, or shared settings. Explanation from http://stackoverflow.com/a/4414911 for which this code is based: * Make an array of objects that contain the needed elements for the requests. * Make a function that accepts the array. * The function removes the first item from…
// recursive ajax (based on code from from http://stackoverflow.com/a/4414911)
function recursiveAjax( arrSettings, commonSettings, raData ) {
if ( typeof raData === "undefined" ) raData = { total: arrSettings.length };
raData.index = raData.total - arrSettings.length;
var currentSettings = arrSettings.shift(); // Remove the first item from the Array.
var defaultSettings = { raTimeout: 100, raFinished: function( raData ){/* do nothing */} };
var settings = $.extend( {}, defaultSettings, commonSettings, currentSettings );
setTimeout( function() {
$.ajax($.extend({},settings,{
success: function( data, textStatus, jqXHR ) {
settings.success( data, textStatus, jqXHR, raData );
if( arrSettings.length ) {
recursiveAjax( arrSettings, commonSettings, raData ); // If there are items left in the Array, make a recursive call
} else {
settings.raFinished( raData );
}
}
}));
}, settings.raTimeout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment