Search code examples
javascriptjqueryajaxxmlhttprequestjqxhr

Ajax jQuery multiple calls at the same time - long wait for answer and not able to cancel


My problem is as follows:

  • On a page, I am doing multiple (6) ajax calls (via jQuery) to fetch some data at the same time (using php wrapper to fetch the data via the calls)
  • The requests are made at the same time and it takes them 10-20 seconds to complete
  • If user clicks on any of the links to go somewhere else (to some other page), I can see that all the calls that didn't complete get cancelled
  • However, the browser still waits for 20 seconds to navigate to the other page - it is like it is still waiting for the longest call to complete, even if it is cancelled

(Same issue is happening in Chrome and Firefox, ajax calls are asynchronous...I have tried to set ajax timeout, to capture readystate=o in ajax error response, even tried to do something with webworkers, to no avail)

Any insight would be helpful

Thanks!


Solution

  • That is due to the maximum number of connections of the browser to a single domain.

    See Browserscope for mamimum per browser.

    • IE 8+9: 6 connections
    • IE 10: 8 connections
    • Chrome 26: 6 connections
    • Firefox 21: 6 connections

    What you could do is collect all Defferred objects and cancel them when the use clicks on a link.

    example:

    // some ajax calls
    doAjax({});
    doAjax({});
    
    var requests = [];
    
    // helper function to perform and register calls
    function doAjax(options) {
        var jqXHR= $.ajax(options);
        requests.push(jqXHR);
        jqXHR.always(function(jqXHR) {
             var index = requests.indexOf(jqXHR);
             if (index!=-1) {
                 requests.splice(index, 1);
             }
        });
    }
    
    // function to abort all calls
    // when your application has a router to provide navigation, this function
    // is typically called when you navigate to another page
    function abortAllPendingRequests() {
        var i;
        for (i=0; i<requests.length; i++) {
            var xhr = requests[i];
            // already finished calls (readyState 4) should not be aborted
            if (xhr.readyState != 4) {
                xhr.abort();
            }
        }
    };
    

    All is left is calling the abortAllPendingRequests function when the user tries to navigate to another page.

    When you have some sort of router (e.g. Backbone.Router) you could call it there.

    If your application does not have a router for navigating, but you make use of plain anchor links, you could add an onClick to the links which calls the abortAllPendingRequests function.