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.
You are re-creating a new LOCAL variable called
showNo, this is not referencing the GLOBAL variable calledshowNo.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: