I am trying to call a setTimeout from within a setInterval callback:
function callback()
{
//assign myVar
var myVar = document.getElementById("givenID");
//...
//now wait 2 secs then call some code that uses myVAr
setTimeout("myVar.innerHTML = 'TEST'", 2000);
}
setInterval("callback();", 10000);
setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope.
What's the best way to solve this?
Run it in Firefox and check Tools | Error Console. if setTimeout fails it may tell you why there.
Also, try replacing
"someFunction();"
with"alert('hi')"
(no semicolon) and see if that works. If so, the problem is narrowed down significantly.This is a perfect candidate for closures:
Your problem is scope related, and this would work around that.
As a matter of best-practice, try not to use strings as parameters to
setTimeout
andsetInterval
because that will invokeeval
... Using the following form might also make this problem easier to understand/debug:I had a similar problem. The issue was that I was trying to call a method from within itself through a setTimeout(). Something like this, WHICH DIDN'T WORK FOR ME:
The following ALSO DIDN'T WORK:
The solution was to use with() statement like so:
Of course, this is an endless cycle, but the point I'm making here is different.
Hope this helps :)