5

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

Community
  • 1
  • 1
Aishwat Singh
  • 4,331
  • 2
  • 26
  • 48
  • About your FIXME comment: [@Mozila](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/timeout) is a note about it. – Bob S Jun 14 '17 at 15:53

2 Answers2

7

Add xhr.timeout after the xhr.open method.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
NaiveCoder
  • 957
  • 3
  • 14
  • 34
  • absolutely. It is documented : https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest/timeout#Compatibilit%C3%A9_des_navigateurs – stloc Aug 17 '20 at 10:26
1

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.

trojan
  • 19
  • 3