homepage Welcome to WebmasterWorld Guest from 54.205.254.108
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
setInterval loop
sssweb




msg:4401235
 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




msg:4401254
 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




msg:4401336
 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




msg:4401348
 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




msg:4401369
 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




msg:4401374
 8:05 pm on Dec 25, 2011 (gmt 0)

...And also change:

var num2 = 1;

to

num2 = 1;

penders




msg:4401378
 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