我有这行代码以指定的时间间隔(SigWebRefresh
毫秒)调用函数50
。
tmr = setInterval(SigWebRefresh, 50);
SigWebRefresh
执行XMLHTTPRequest
:
function SigWebRefresh(){
xhr2 = new XMLHttpRequest();
xhr2.open("GET", baseUri + "SigImage/0", true );
xhr2.responseType = "blob";
xhr2.onload = function (){
var img = new Image();
img.src = getBlobURL(xhr2.response);
img.onload = function (){
Ctx.drawImage(img, 0, 0);
revokeBlobURL( img.src );
img = null;
}
}
xhr2.send(null);
}
我使用clearInterval
清除了使用setInterval()方法设置的计时器。
clearInterval(tmr);
我想中止所有XMLHttpRequest,但xhr2.abort();
只中止一个请求实例。如何中止所有未完成的XmlHttpRequest
?
答案 0 :(得分:3)
尝试将每个xhr2
变量推送到数组,利用Array.prototype.forEach
中止存储的每个xhr2
变量
var requests = [];
function SigWebRefresh(){
xhr2 = new XMLHttpRequest();
requests.push(xhr2);
xhr2.open("GET", baseUri + "SigImage/0", true );
xhr2.responseType = "blob";
xhr2.onload = function (){
var img = new Image();
img.src = getBlobURL(xhr2.response);
img.onload = function (){
Ctx.drawImage(img, 0, 0);
revokeBlobURL( img.src );
img = null;
}
}
xhr2.send(null);
}
// abort all requests
requests.forEach(function(request) {
request.abort()
})
答案 1 :(得分:0)
您可以实现所有处理请求的列表:
function remove(array, element){
var index = array.indexOf(element);
if (index > -1) {
array.splice(index, 1);
}
}
var all_requests = [] // The list of requests that are processing
function SigWebRefresh(){
var xhr2 = new XMLHttpRequest();
xhr2.open("GET", baseUri + "SigImage/0", true );
xhr2.responseType = "blob";
xhr2.onload = function (){
var img = new Image();
img.src = getBlobURL(xhr2.response);
img.onload = function (){
Ctx.drawImage(img, 0, 0);
revokeBlobURL( img.src );
img = null;
remove(all_requests, xhr2); // Make sure to remove already finished requests from your list
}
}
xhr2.send(null);
all_requests.push(xhr2); // Add processing request to the list
}
然后澄清:
for(var i in all_requests)
all_requests[i].abort();
all_requests = [] // Clear the list of requests
答案 2 :(得分:0)
var xhr2 = null;
function SigWebRefresh(){
if( xhr2 != null ) {
xhr2.abort();
xhr2 = null;
}
xhr2 = new XMLHttpRequest();
xhr2.open("GET", baseUri + "SigImage/0", true );
xhr2.responseType = "blob";
xhr2.onload = function (){
var img = new Image();
img.src = getBlobURL(xhr2.response);
img.onload = function (){
Ctx.drawImage(img, 0, 0);
revokeBlobURL( img.src );
img = null;
}
}
xhr2.send(null);
}