简体   繁体   English

如果加载时间很长,如何中止 XMLHttpRequest?

[英]How to abort XMLHttpRequest if taking a lot of time to load?

I have recently started using XMLHttpRequest.我最近开始使用 XMLHttpRequest。 Is there a way to abort the request if a request is taking too much time to give a response?如果请求花费太多时间来给出响应,有没有办法中止请求? and Another question when I make a request why am I not able to do console.log in XMLHttpRequest.onprogress?和另一个问题,当我提出请求时,为什么我无法在 XMLHttpRequest.onprogress 中执行 console.log?

let xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function () {
       if(this.readyState === 4)
           resolve(something)
}
xhr.onprogress = function () {
   console.log("loading..") // not printing
}

 xhr.open('GET', url);
//headers
xhr.send();

To abort simply use xhr.abort() method and it will cancel your request.要中止,只需使用xhr.abort()方法,它将取消您的请求。 Also as you don't want it to cancel unless it's working so you can set a time limit within which abort will be executed if the response is not retrieved.此外,除非它正在工作,否则您不希望它取消,因此您可以设置一个时间限制,如果未检索到响应,将在该时间限制内执行中止。

Also take a variable isReceived and set it to false.还要取一个变量isReceived并将其设置为 false。 Now if the response is received it will be set to true and the abort() method won't be executed.现在,如果收到响应,它将设置为 true,并且不会执行 abort() 方法。 else if it is not received within the desired time, it will remain false and will be aborted否则,如果在期望的时间内没有收到,它将保持为假并被中止

let isReceived = false;
let xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function () {
       if(this.readyState === 4)
           isReceived = true;
           resolve(something)
}
xhr.onprogress = function () {
   console.log("loading..") // not printing
   setTimeout(function(){  
     if(!isReceived){
     xhr.abort(); 
    }
   }, 2000);
}

 xhr.open('GET', url);
//headers
xhr.send();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM