Welcome to WebmasterWorld Guest from 54.167.86.59

Forum Moderators: open

Message Too Old, No Replies

setInterval loop

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

Preferred Member

10+ Year Member

joined:Nov 10, 2005
posts: 387
votes: 0


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)

Senior Member

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

joined:July 3, 2006
posts: 3123
votes: 0


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)

Preferred Member

10+ Year Member

joined:Nov 10, 2005
posts:387
votes: 0


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)

Senior Member

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

joined:July 3, 2006
posts: 3123
votes: 0


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)

Preferred Member

10+ Year Member

joined:Nov 10, 2005
posts:387
votes: 0


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)

Preferred Member

10+ Year Member

joined:Nov 10, 2005
posts:387
votes: 0


...And also change:

var num2 = 1;

to

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

Senior Member

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

joined:July 3, 2006
posts: 3123
votes: 0


Yes, that should do it.
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members