Javascript – Delay between multiple ajax calls

javascript, jquery

I have 5 ajax calls that look like this (not posting all five):

tabTest = {BASE_URL : 'http://localhost/project/',getPics : function(){    $.ajax({        type : 'GET',        url : this.BASE_URL +'js/image1.js',        dataType : "json",        async: false,        success: function(data){            var pic = data.images.image[0].image_one;                $('#pic1 img').attr("src", pic);        }       });    $.ajax({        type : 'GET',        url : this.BASE_URL +'js/image2.js',        dataType : "json",        async: false,        success: function(data){            var pic = data.images.image[0].image_two;                           $('#pic2 img').attr("src", pic);        }       });   }};

The ajax calls do work but they all fire at once; instead, I need to put a delay between each one so they do not fire all at once but rather in order only once (upon click, which happens in a different function) with 5 seconds between each call.

I've tried using 'setTimeout' but it has not worked yet. I'm really not sure how to proceed on this one.

Best Solution

If you put your AJAX calls its own setTimeout() there's no reason why it shouldn't work:

setTimeout(function(){    $.ajax({        type : 'GET',        url : this.BASE_URL +'js/image1.js',        dataType : "json",        async: false,        success: function(data){            var pic = data.images.image[0].image_one;            $('#pic1 img').attr("src", pic);        }       });}, 5000);

And then increment the duration by 5000 for each call. So the second would look like:

setTimeout(function(){    $.ajax({        type : 'GET',        url : this.BASE_URL +'js/image2.js',        dataType : "json",        async: false,        success: function(data){            var pic = data.images.image[0].image_one;            $('#pic2 img').attr("src", pic);        }       });}, 10000);

You could also put the functions inside the previous request's callback although a request fail would mean that all subsequent AJAX requests wouldn't get called.