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 };

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
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.
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.
Add xhr.timeout after the xhr.open method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With