user663724
user663724

Reputation:

How to set a conditional delay for making a request?

I have an array of symbols as shown below. For each element of the array I am making an Ajax request.

var symbols = ["SSS", "SEE"]

$(document).ready(function () {
    $.each(symbols, function (index, value) {
        loadXMLDoc(value);
    });
});

function loadXMLDoc(value) {
    $.ajax({
        type: 'POST',
        url: 'https://ganaga/aaaa/sss',
        success: function (data) {}
    }

In the browser console, I see many XHR requests under pending state. Is it possible to make the next Ajax request only when the response has been obtained for the previous array element?

Upvotes: 0

Views: 67

Answers (3)

sites
sites

Reputation: 21795

var symbols = ["SSS", "SEE"]

$(document).ready(function () {
   loadXMLDoc(symbols);
});

function loadXMLDoc(symbols) {
   if(symbols[0]) {
      $.ajax({
        type: 'POST',
        url: 'https://ganaga/aaaa/sss',
        success: function(data){ loadXMLDoc(symbols.slice(1)) }
      });
   }
}

There is no value being used in loadXMLDoc in your question, I suppose you want:

        url: 'https://ganaga/aaaa/'+ symbols[0],

Also, I would rename function to loadXMLDocs.

Upvotes: 2

Barmar
Barmar

Reputation: 781068

Invoke the next AJAX call in the callback function.

function loadXMLDoc(n) {
    var value = symbols[n];
    $.ajax({
        type: 'POST',
        url: 'https://ganaga/aaaa/sss',
        success: function (data) {
            if (n < symbols.length-1) {
                loadXMLDoc(n+1);
            }
        }
    }
}

Start it with:

loadXMLDoc(0);

Upvotes: 1

Jason P
Jason P

Reputation: 27012

I would just use a little recursion:

var symbols = ["SSS", "SEE"]

$(document).ready(function () {
    loadXMLDoc(0);
});

function loadXMLDoc(idx) {
    value = symbols[idx];
    if (value) {
        $.ajax({
            type: 'POST',
            url: 'https://ganaga/aaaa/' + value,
            success: function (data) {
                //...
                loadXMLDoc(idx+1);
            }
        });
    }
}

Upvotes: 1

Related Questions