Welcome to WebmasterWorld Guest from 54.167.144.170

Forum Moderators: open

setInterval loop

   
8:04 pm on Dec 24, 2011 (gmt 0)

5+ Year Member



I must be missing something simple, but can someone explain why the following occurs in a function running on setInterval:

var num = 10;

function my() {
if (num2){
// script never gets here
}
else {
num--;
if (num<1) {
var num2 = 1;
}
}
}

I've verified that it initializes num2, but it never goes in the first conditional.
10:34 pm on Dec 24, 2011 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Because num2 is declared as a local variable... local to the my() function. When my() exits, num2 is lost.

You need to declare num2 as global, as you do with num.
2:11 pm on Dec 25, 2011 (gmt 0)

5+ Year Member



I figured it was soemthing like that, but why then doesn't it also 'lose' the decremented value of num?

Anyway, I ended up using a work-around that does what I need. Thanks penders.
4:15 pm on Dec 25, 2011 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



You're welcome.

...but why then doesn't it also 'lose' the decremented value of num?


Because num is declared in the global scope. It is declared (with the var keyword) outside of any function and therefore exists everywhere (ie. it is 'global').
6:38 pm on Dec 25, 2011 (gmt 0)

5+ Year Member



So all I needed to do was add:

var num2 = 0;

after

var num = 10;

Is that right?
8:05 pm on Dec 25, 2011 (gmt 0)

5+ Year Member



...And also change:

var num2 = 1;

to

num2 = 1;
8:18 pm on Dec 25, 2011 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Yes, that should do it.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month