setTimeout连续循环,无需等待

时间:2013-01-22 16:31:24

标签: javascript html ajax

我正在尝试让setTimeout在15秒后重新运行它内部的函数,它不会等待15秒并且只是在一个恒定循环中执行它。

这是我当前的代码

function checkSession(x) {
http.abort();
http.open("GET", siteURL+"processes/ajax.php?call=check_session&string="+x+"&new="+Math.random(), true);
http.onreadystatechange = function() {
    if(http.readyState == 4) {
        if(http.responseText == true) {
            updateSession(x);
        } else {
            setTimeout(checkSession(x),15000);
        }
    }
}
http.send(null);
}

我没有看到代码本身有任何问题,唯一不对的是它只是在不等待“15000”毫秒的情况下进行一个恒定的循环。

2 个答案:

答案 0 :(得分:9)

将setTimeout调用更改为:

setTimeout(function(){checkSession(x)},15000);

正如您现在所做的那样,立即调用checkSession,然后将其作为参数传递给setTimeout。将其包含在函数内部允许延迟调用。

答案 1 :(得分:1)

你的解释:

功能如下:setTimeout( function, delay );

您的方法调用未将函数的匿名函数或引用设置为函数参数。

错误:setTimeout(checkSession(x),15000);

原因:checkSession(x)是一个函数调用,而不是对函数或匿名函数的引用

右:setTimeout(function() {checkSession(x) },15000);

原因:函数调用现在被包装为一个匿名函数,并为setTimeout( function, delay )方法设置了函数参数。

希望有助于为您清理它!