Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created November 3, 2011 11:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Integralist/1336279 to your computer and use it in GitHub Desktop.
Save Integralist/1336279 to your computer and use it in GitHub Desktop.
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
Copy link

yaa110 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
Copy link

zigri2612 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