Last active
May 31, 2025 20:38
-
-
Save Integralist/1336279 to your computer and use it in GitHub Desktop.
cancel all jQuery AJAX requests #js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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); | |
} | |
}); |
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
Thank you for the gist, we could also remove a completed request from the array: