Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setInterval loop not holding variable

Here is my code:

    var showNo = 1;     
    window.setInterval(function() {
          console.log(showNo);
          if(showNo === 1) { var nextNo = 2;  }
          else if(showNo === 2) { var nextNo = 3;  }
          else if(showNo === 3) { var nextNo = 4;  }
          else if(showNo === 4) { var nextNo = 5;  }
          else if(showNo === 5) { var nextNo = 1;  }
          else { var showNo = 1; var nextNo = 2; }

          var showNo = nextNo;
          }, 500);

My question is, why is the showNo variable not holding when the setInterval loop starts? The console displays 'undefined' in the above example. This may be a simple question, but I am trying to teach myself query and this has me stuck..

Any answers would be great.

Thanks.

like image 318
Ryan Avatar asked Apr 23 '26 11:04

Ryan


1 Answers

You are re-creating a new LOCAL variable called showNo, this is not referencing the GLOBAL variable called showNo.

It is very bad practice to use global variables, I advise wrapping this inside of an anonymous function

I think this is what you're looking to do:

  (function() {
      var showNo = 1;     
      window.setInterval(function() {
            console.log(showNo);

            if( showNo >== 1 && showNo <== 4 ) {  
                showNo++;
            } else if( showNo === 5 ) {
                showNo = 1;  
            } else { 
                showNo = 2; 
            }

            }, 500);
    })();
like image 187
Jacob Relkin Avatar answered Apr 26 '26 01:04

Jacob Relkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!