我有以下javascript。

function isOnline() {

var status = navigator.onLine ? 'online' : 'offline',
    indicator = document.getElementById('indicator'),
    current = indicator.textContent;

// only update if it has change
if (current != status) {

    // update DOM
    indicator.textContent = status;

    // trigger handler
    handler[status]();
};

if(current == 'offline')
{
  setInterval(checkServerStatus, 500)
  checkServerStatus();
 }
};




function checkServerStatus()
{
var img = document.createElement("img");
img.onload = function()
{
    alert('yey!');
    setInterval(isOnline, 500);
    isOnline();
};
img.onerror = function()
{
    alert('meh.')
};
img.src = "image-small.jpg";  //image on server(should be small so that intermittent checks are not bad)
}
$(checkServerStatus);


我想做的是以下内容。
首先调用checkServerStatus()->如果每500毫秒在线运行isOnline()以继续检查网站的状态。在我的isOnline代码中,如果我曾经检查过它是否处于脱机状态,则再次运行checkServerStatus,如果我仍然处于连接状态,请返回。

另外,我想在此添加两件事,当checkServerStatus失败时,递归调用另一个函数isOnline2进行检查,直到它在线为止,然后在此我再次调用checkServerStatus。

我当前遇到的问题是checkServerStatus始终显示“ yey”警报。我以为,该函数仅启动一次,然后使用setInterval(isOnline,500)将继续运行。将isOnline更改为脱机之后,然后我将再次运行checkServerStatus函数。

任何有关如何调整这一点的想法将不胜感激。

最佳答案

将间隔设置为变量,然后在要停止间隔时使用clearInterval()。

var interval = setInterval();
clearInterval(interval);

关于javascript - 用于在线状态的递归Javascript函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17456500/

10-12 20:16