Javascript - 在函数中使用 clearInterval 后重新激活 setInterval

Javascript - Reactivating setInterval after using clearInterval from a function

我正在开发一个检查互联网连接的功能(工作正常)和一个每 20 秒刷新一次页面的功能。我一直在研究的另一个功能是检测互联网状态何时发生变化并停止刷新功能。我试图让它工作,所以当互联网恢复在线时,刷新功能再次启动。我已经尝试了多种修复,但没有任何效果。

这是一些代码:

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);

一切正常,直到互联网连接恢复在线,然后刷新功能不会再次启动。这就是我要解决的问题。

谢谢。

首先,您实际上并没有阻止页面刷新。

您的互联网检查功能应该停止刷新,如下所示:

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!
        }
    }
}

其次,您的页面可能不会刷新,因为 refresh() 函数不存在:

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

应该就这些了!希望你的项目顺利!