JavaScript setInterval loop not containing a 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 held when the setInterval loop starts? In the above example, the console displays "undefined". This may be a simple question, but I'm trying to teach myself how to use it, and it made me stuck.

Any answers would be great.

Thank.

+3
source share
5 answers

You create a new LOCAL variable with the name showNo, this does not apply to the GLOBAL variable with the name showNo.

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

I think this is what you want 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);
    })();
+10
source

, @Jacob, , :

var showNo = 1;     
window.setInterval(function() {
      console.log(showNo);
      showNo++;
      if(showNo > 4)
          showNo = 1;
      }, 500);
+1

Javascript Closures, , JavaScript.

+1

JavaScript var , . . , :

var showNo = 1;     
    window.setInterval(function() {
          var showNo; // I'm localizing it
          var showNo; // and again
          var nextNo; // Now I'm declaring a new variable
          var nextNo; // and I just can't stop
          var nextNo; // myself from declaring it again
          var nextNo; // its like beating
          var nextNo; // a
          var nextNo; // dead horse.
          console.log(showNo);
          if(showNo === 1) { nextNo = 2;  }
          else if(showNo === 2) { nextNo = 3;  }
          else if(showNo === 3) { nextNo = 4;  }
          else if(showNo === 4) { nextNo = 5;  }
          else if(showNo === 5) {  nextNo = 1;  }
          else { showNo = 1; nextNo = 2; }

          showNo = nextNo;
          }, 500);

, .

. javaScript, .

+1

.

function hello(){
    var count = 0;
    var timer = setInterval( function(){  count+=1;alert(count); },2000);
}
0

Source: https://habr.com/ru/post/1736856/


All Articles