I am coding a native JavaScript application in which I make simultaneous AJAX requests to multiple unique servers every minute. When a server is offline, I intended my program to handle this through the function registered to the XHR.ontimeout event.
Below is a quick JS sample I wrote to demonstrate my problem. Monitor the console and you will see only sometimes requests to an offline address trigger the ontimeout event. Other times ERR_CONNECTION_TIMED_OUT occurs. I would like to have a timeout handler that executes every time I call my function and the server is offline.
<!DOCTYPE html>
<html>
<TITLE>Timeout Error Demo</TITLE>
<body>
<script>
var i=0;
var xhr;
function main(){
console.log('Main run #'+i);
i++;
xhr=new XMLHttpRequest();
xhr.open("GET", "http://1.1.1.1", true); //this address is always offline
xhr.timeout=2000;
xhr.ontimeout=function(){
console.log("timed out");
}
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
console.log("done");
}
}
xhr.send(null);
setTimeout(main,5000);
}
main();
</script>
</body>
</html>