Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Try to cancel all jQuery AJAX requests currently running
$.xhrPool = [];
$.xhrPool.abortAll = function() {
/* Original example used _underscore api
_.each(this, function(jqXHR) {
jqXHR.abort();
});
*/
$.each(this, function(jqXHR) {
jqXHR.abort();
});
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
}
});
@yaa110

This comment has been minimized.

Copy link

commented Jul 19, 2016

Thank you for the gist, we could also remove a completed request from the array:

$.xhrPool = [];

$.xhrPool.abortAll = function() {
    $.each(this, function(jqXHR) { 
        jqXHR.abort(); 
    });
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.xhrPool.indexOf(jqXHR);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});
@zigri2612

This comment has been minimized.

Copy link

commented Sep 29, 2016

Better to use independent code.....

var xhrQueue = []; 

$(document).ajaxSend(function(event,jqxhr,settings){
    xhrQueue.push(jqxhr); //alert(settings.url);
});

$(document).ajaxComplete(function(event,jqxhr,settings){
    var i;   
    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
        xhrQueue.splice(i,1); //alert("C:"+settings.url);
    }
});

ajaxAbort = function (){  //alert("abortStart");
    var i=0;
    while(xhrQueue.length){ 
        xhrQueue[i++].abort(); //alert(i+":"+xhrQueue[i++]);
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.