views:

1422

answers:

4

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?

+2  A: 

It seems to work for me. What do you mean by "failing"? And what browser/etc. are you using?

jtbandes
Alert was working for me too with previous example - so the problem is not related to the setTimeout in there, thanks for pointing out, I edited the question.
JohnIdol
+1  A: 

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.

Michael Gundlach
cheers - I did this and noticed the problem wasn't related to setTimeout - see edit
JohnIdol
+3  A: 

As a matter of best-practice, try not to use strings as parameters to setTimeout and setInterval because that will invoke eval ... Using the following form might also make this problem easier to understand/debug:

setInterval(function () {
    // do stuff
    // ...
    // now wait 2 secs then call someFunction
    setTimeout(someFunction, 2000);
}, 10000);
Andrew Hedges
great suggestion - thanks
JohnIdol
+9  A: 

This is a perfect candidate for closures:

setInterval(
    function ()
    {
       var myVar = document.getElementById("givenID");
       setTimeout(
          function()
          {
              // myVar is available because the inner closure 
              // gets the outer closures scope
              myVar.innerHTML = "Junk";
          },2000);
    }, 10000);

Your problem is scope related, and this would work around that.

FlySwat
I guess you're right - I edited the question
JohnIdol
Thus illustrating an excellent reason not to pass strings as parameters to setTimeout and setInterval! :-)
Andrew Hedges
sure Andrew - I voted you up :-)
JohnIdol
sweet... very sweet...
elcuco