Search code examples
javascriptsetintervalintervalsclearinterval

JavaScript: clearInterval won't clear interval


I have an unusual problem. I'm using the following script to check for internet connection using navigator.onLine. If there is internet connection, the page will be refreshed every 15 seconds. If there isn't any internet connection, the page will use innerHTML to display a message.

<script type="text/javascript">
setInterval(function () {
if (navigator.onLine) {
var myInterval = setInterval(function(){window.location.href = "Tracker.html";},15000);
} else {
clearInterval(myInterval);
var changeMe = document.getElementById("change");
change.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
}
}, 250);
</script>

My problem is, once there is no internet connection, the message will be displayed, BUT the page would still be refreshed one last time. I'm trying to avoid this, by using clearInterval(myInterval); in the else part of the code, however it won't work.

Any suggestions?


Solution

  • To refresh the page at 15 second intervals (provided that a connection is present), use:

    function refresh() {
        if(navigator.onLine)
            window.location.href = "Tracker.html";
        else{
            var changeMe = document.getElementById("change");
            change.innerHTML = "<big><font face='Arial' color='#ffffff' size='2'><center>OFFLINE</big><br>No internet connection</font></center>";
            setTimeout(refresh, 250);
        }
    }
    setTimeout(refresh, 15000);
    

    At the end of 15 seconds, this checks whether a connection is present. If there is, it refreshes the page. If there isn't, it proceeds to check every 250 milliseconds afterwards until the user is reconnected, at which point it refreshes the page.

    The net result is that the script refreshes the page as soon as possible after a minimum of 15 seconds have elapsed.

    Here is a demonstration: http://jsfiddle.net/JGEt9/show