0

I'm working on a function that checks internet connectivity (works fine) and a function that refreshes the page every 20 seconds. Another function I've been working on detects when the internet state changes and stops the refresh function. I'm trying to make it work so when the internet comes back online, the refresh function starts again. I've tried multiple fixes but nothing is working.

Here's some code:

function checkNetConnection()
{
    var xhr = new XMLHttpRequest();
    var file = "http://i.imgur.com/FIKb6D8.png";
    var r = Math.round(Math.random() * 10000);
    xhr.open('HEAD', file + "?rand=" + r, false);
    try {
        xhr.send();
        if (xhr.status >= 200 && xhr.status < 304) {
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}

function modalCheck()
{
    var status = checkNetConnection();
    if(status == false) {
        document.getElementById('mymodal').style.display = "block";
    } else {
        document.getElementById('mymodal').style.display = "none";
    }
}

var int1 = setInterval(modalCheck, 7000);

function refreshPage()
{
    var state = checkNetConnection();
    if(state == false)
    {
        clearInterval(int2);
    } else {                    
        location.reload(true);
        alert("PAGE RELOADED!"); /* Testing purposes! */
    }
}

var int2 = setInterval(refresh, 12000);

Everything works fine until the internet connection comes back online, then the refresh function doesn't start again. This is what I'm trying to fix.

Thanks.

clintgx
  • 25
  • 7
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Alexander O'Mara Mar 31 '16 at 03:14

1 Answers1

1

First of all, you never actually stop the page from refreshing.

Your internet-checking function should stop the refresh, like this:

function modalCheck()
{
    var status = checkNetConnection();
    if(status == false) {
        document.getElementById('mymodal').style.display = "block";

        clearInterval(int2); //Connection lost! DO NOT REFRESH
        int2 = null; //So the next if statement can detect whether the interval is going or not

    } else {
        document.getElementById('mymodal').style.display = "none";

        if(!int2) { //So interval isn't doubled up!
          int2 = setInterval(refresh, 12000); //Connection regained!
        }
    }
}

Secondly, your page probably doesn't refresh because the refresh() function doesn't exist:

setInterval(refresh, 12000); //should be "refreshPage"

That should be all! Hope your project goes well!

Aaron Gillion
  • 2,227
  • 3
  • 19
  • 31
  • 1
    Thanks mate! Works perfectly. Yeah I copied some older code so that's why refresh was misnamed. – clintgx Mar 31 '16 at 03:28