1

我试图让 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”毫秒。

4

2 回答 2

9

将 setTimeout 调用更改为:

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

正如你现在所拥有的,checkSession 会立即被调用,然后作为参数传递给 setTimeout。将其包装在函数中允许延迟调用。

于 2013-01-22T16:32:13.283 回答
1

你的解释:

函数是这样的:setTimeout( function, delay );

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

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

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

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

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

希望这有助于为您清除它!

于 2013-01-22T16:38:10.357 回答