In a XMLHTTPRequest
, how to use time-out condition such that if there is no response from the server for a fixed amount of time (say 5 seconds) then it should display an error message?
In other words, the request should wait for 5 seconds, if there is no response from the server then it should display a message saying "Time out. Please try again later". It would be better if the code can work for both Synchronous and Asynchronous.
The following code I am using without time-out condition.
function testXMLHTTP()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else if(xmlhttp.readyState < 4)
{
document.getElementById("myDiv").innerHTML="Loading...";
}
}
xmlhttp.open("GET","abcd.php",true);
xmlhttp.send();
}