Home > Net >  javascript ajax: How do I run the ajax in the loop?
javascript ajax: How do I run the ajax in the loop?

Time:12-26

here is my code

        for (i = 0; i < 100; i  ) {
         $.ajax({
            url: "APIurl",
            type    : "POST",
            data    : "a=addsgstkw",
            success: function (data) {
              alert(data);
            }
         });
        }

My problem is that the ajax in the loop is not executed to the end. It stops after a few runs. For example, after 10 times. How do I run the ajax in the loop?

CodePudding user response:

There are browser-specific limits to the number of parallel network requests you may have that connect to the same domain. This is true of most, if not all, modern browsers.

If you wish to have these requests occur in parallel, then consider creating a queue of requests that need to be executed. Then execute up to a certain number of these ajax requests simultaneously. Whenever one of these ajax requests finishes executing, have it remove the next one from the queue and execute it.

Something like the following may work:

let request_queue = [];
for(let i = 0; i < 100; i  ) {
    request_queue.push({
        url: 'APIUrl',
        type: 'POST',
        data: 'a=addsgstkw',
        success: function(data) {
            alert(data);
        },
        complete: function() {
            // After this request finishes, whether it succeeds or fails, take the next request and execute it.
            let next_request = request_queue.pop();
            if(next_request) {
                $.ajax(next_request);
            }
        }
    });
}

// Starts two parallel network requests.
$.ajax(request_queue.pop());
$.ajax(request_queue.pop());

This will be slower than running potentially every single request in parallel (if your network can handle the bandwidth), but unfortunately there's not really a way around that problem. Some solution like the above will be necessary in order to limit the rate at which you're making these requests.

  • Related