javascript - setTimeout continuous loop without wait - Stack Overflow

I'm trying to get setTimeout to re-run the function it's inside after 15 seconds, it's n

I'm trying to get setTimeout to re-run the function it's inside after 15 seconds, it's not waiting 15 seconds and just doing it in a constant loop.

Here's my current code

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

I don't see any problems in the code itself, the only thing wrong is that it's just doing a constant loop without waiting the "15000" miliseconds.

I'm trying to get setTimeout to re-run the function it's inside after 15 seconds, it's not waiting 15 seconds and just doing it in a constant loop.

Here's my current code

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

I don't see any problems in the code itself, the only thing wrong is that it's just doing a constant loop without waiting the "15000" miliseconds.

Share Improve this question asked Jan 22, 2013 at 16:31 Curtis CreweCurtis Crewe 339 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

change the setTimeout call to:

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

As you have it now, checkSession is called immediately and then passed as an argument to setTimeout. Wrapping it inside the function allows for the call to be deferred.

Your explanation:

The function is like this: setTimeout( function, delay );

Your method call was not setting an anonymous function or reference to a function as the function argument.

Wrong: setTimeout(checkSession(x),15000);

Reason: checkSession(x) is a function call, not a reference to a function or anonymous function

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

Reason: the function call is now wrapped as an anonymous function in place and the function argument is set for the setTimeout( function, delay ) method.

Hope that helps to clear it up for you!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744966746a4603727.html

相关推荐

  • javascript - setTimeout continuous loop without wait - Stack Overflow

    I'm trying to get setTimeout to re-run the function it's inside after 15 seconds, it's n

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信