简体   繁体   中英

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

I have recently started using 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?

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. 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. Now if the response is received it will be set to true and the abort() method won't be executed. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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