中止 XMLHttpRequest 的所有实例

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 变量推入数组,利用 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);
 }