Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xhr timeout gives invalid state error in ie11

Am trying to set timeout in XMLHttpRequest but it shows invalid state error, here's the code

function get(url, options) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    // headers
    if (options && options.headers) {
      for (let header in options.headers) {
        if (options.headers.hasOwnProperty(header)) {
          xhr.setRequestHeader(header, options.headers[header]);
        }
      }
    }

    xhr.open('GET', url);
    // FIXME: Why is IE11 failing on "xhr.timeout?
    // xhr.timeout = 10000;

    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        try {
          const data = JSON.parse(xhr.responseText);
          resolve(data);
        } catch (ex) {
          reject({
            status: this.status,
            statusText: xhr.statusText
          });
        }
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };

    xhr.ontimeout = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };

    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };

    xhr.send();
  });
}

export default { get };

enter image description here

I had a look at following links link1 link2 link3 and specifically kept xhr.timeout between xhr.open and xhr.send

I even tried this

xhr.onreadystatechange = function () {
  if(xhr.readyState == 1 ) {
    xhr.timeout = 5000;
  }
};

But no luck

like image 661
Aishwat Singh Avatar asked Apr 12 '17 05:04

Aishwat Singh


People also ask

What is xhr timeout?

The XMLHttpRequest. timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout.

Is there a way to limit the time an Ajax call will run using XMLHttpRequest?

According to the specs, the timeout value defaults to zero, which means there is no timeout. However, you can set a timeout value on the XHR. timeout property; the value is in milliseconds.


2 Answers

Add xhr.timeout after the xhr.open method.

like image 167
NaiveCoder Avatar answered Oct 16 '22 15:10

NaiveCoder


You should set xhr.timeout only when you call xhr.open() in asynchronous mode, otherwise MSIE will rise an exception INVALID_STATE_ERR.

Example: xhr.open("POST", url, true);

ps. Strangely, i don't see this issue in FF & Chrome.

like image 38
trojan Avatar answered Oct 16 '22 16:10

trojan