Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript: Stop SetInterval if no response
    text
    copied!<p>I'm using an alternate code to <code>navigator.OnLine</code> to check for network connection. It works, however, I'm having some issues with it.</p> <p>If I'm connected/disconnected to the network inside the intranet (corporate network) , then I have no issues whatsoever. However, if I'm home and I'm connected to my home network, but not connected to the corporate intranet using a VPN connection, then the window will freeze for 10 second intervals. I think it's because there's internet connection, but the server is unreachable because I'm disconnected from the intranet.</p> <p>Here's the code:</p> <pre><code>function serverReachable() { // IE vs. standard XHR creation var x = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" ), s; x.open( // requesting the headers is faster, and just enough "HEAD", // append a random string to the current hostname, // to make sure we're not hitting the cache "http://16.24.163.33" + window.location.hostname + "/?rand=" + Math.random(), // make a synchronous request false ); try { x.send(); s = x.status; // Make sure the server is reachable return ( s &gt;= 200 &amp;&amp; s &lt; 300 || s === 304 ); // catch network &amp; other problems } catch (e) { return false; } } </code></pre> <p>What I would like to do with your help, is to cancel a request that takes more than one second. So if I'm trying to reach 16.24.163.33 from home, and no response was received after 1 (!) second, then cancel the request, and retry this whole code again in two minutes.</p> <pre><code>setInterval(function () { if (serverReachable()) { if (timeout === null) { var changeIt = document.getElementById('change') changeIt.style.visibility = 'hidden'; timeout = setInterval("refreshIframe()",25000); } } else { clearTimeout(timeout); timeout = null; var changeIt = document.getElementById('change') changeIt.style.visibility = 'visible'; } }, 900); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload