How to stop all incomplete ajax requests without modifying every ajax calls in a project

CodeGuy
March 03, 2016

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. which will enable to update parts of a web page, without refreshing the whole page.
The below snippet uses array xhrPool to store all requests that originate from the source calls and the completed requests are spliced from the array.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$.xhrPool = []; // array of uncompleted requests
$.xhrPool.abortAll = function() { // our abort function
    $(this).each(function(idx, jqXHR) { 
        jqXHR.abort();
    });
    $.xhrPool.length = 0
};

$.ajaxSetup({
    beforeSend: function(jqXHR) { // before jQuery send the request we will push it to our array
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) { // when some of the requests completed it will splice from the array
        var index = $.xhrPool.indexOf(jqXHR);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});

0 comments

Do not spam.

Like us on Facebook

Blog Archive