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 badges2 Answers
Reset to default 9change 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
评论列表(0条)