nemo
nemo

Reputation: 633

setInterval only working inside of if(){} block

So I think there is something key to be picked up from this situation I encountered and was hoping some experience could explain it.

When I run this code, it does NOT work:

t5 = "nikolas"+t4;

setInterval(adds,250);

function adds(){
    if (t4 < 100){
        t4=t4+1;
    }    
    else{
        return;
    }
};

this does DOES work:

t5 = "nikolas"+t4;

adds(t4);

function adds(a){

    if (a < 100){
        a=a+1;
        setInterval(t4=a,250);
    }

    else{
        return;
    }
};

TL;DR: setInterval seems to work inside the if block but not outside. When it works it displays nikolast4 where t4 is an integer that 'ticks' from 1-100 (eg.strong text nikolas0 nikolas1 nikolas2 nikolas3 nikolas4)

Also this code (due to the application I am programming in) is supposed to refresh every 250ms (but take the whole refreshing part with a grain of salt, not totally 100% sure about that).

Upvotes: 0

Views: 3286

Answers (1)

GameAlchemist
GameAlchemist

Reputation: 19294

The code below is fully functionnal, and looks very much like your non-working example.

You can check here : http://jsbin.com/ofezip/1/edit

So i guess you have an issue with the scope of your variables.

window.onload = function()  {

   var myOutput = document.createElement("output"); 
   document.body.appendChild(myOutput);

   var t4 = 0;

   var helloInterval = setInterval(adds,250);

   function adds(){
          if (t4 < 10){
              t4++;
              myOutput.value = "hello " + t4;
          }    
          else {
              myOutput.value = "goodbye" ;
              clearInterval(helloInterval);      
              return;
        }
   }

};

Upvotes: 1

Related Questions