[英]Abort all instances of XMLHttpRequest
我有这行代码以指定的时间间隔( 50
毫秒)调用SigWebRefresh
函数。
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
?
尝试将每个xhr2
变量推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()
})
您可以实现所有处理请求的列表:
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
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.