homepage Welcome to WebmasterWorld Guest from 54.226.147.84
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
setInterval loop
sssweb

5+ Year Member



 
Msg#: 4401233 posted 8:04 pm on Dec 24, 2011 (gmt 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.

 

penders

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



 
Msg#: 4401233 posted 10:34 pm on Dec 24, 2011 (gmt 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.

sssweb

5+ Year Member



 
Msg#: 4401233 posted 2:11 pm on Dec 25, 2011 (gmt 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.

penders

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



 
Msg#: 4401233 posted 4:15 pm on Dec 25, 2011 (gmt 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').

sssweb

5+ Year Member



 
Msg#: 4401233 posted 6:38 pm on Dec 25, 2011 (gmt 0)

So all I needed to do was add:

var num2 = 0;

after

var num = 10;

Is that right?

sssweb

5+ Year Member



 
Msg#: 4401233 posted 8:05 pm on Dec 25, 2011 (gmt 0)

...And also change:

var num2 = 1;

to

num2 = 1;

penders

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



 
Msg#: 4401233 posted 8:18 pm on Dec 25, 2011 (gmt 0)

Yes, that should do it.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved