17

OK, I have read several questions here with the same title but still couldn't find a solution to my problem. I'm working on a basic javascript count down timer and I'm stuck on updating the value of the a variable.

a = 100;
var i = setInterval( function(){ timer( a ); }, 1000 );

function timer( a ){
    console.log( a );
    if( a < 1 ){     
        console.log( 'Reaching Stop' ); 
            clearInterval( i );
            return;         
    } 
    a -= 1;
}

As I'm decrementing the value of a by -1, console.log( a ) should be 1 less every time i.e

100 99 98 ......

But console.log( a ) is always giving 100

newbie to javascript here please be gentle. thanks.

0

2 Answers 2

16

You should not pass a in parameter of timer function to access the global variable a. When a is passed to timer function the value of global variable is used but in timer the parameter variable is local to timer function and changing the value of it wont change the value of global variable. It means you have two variables in your code having name a one is global and other is local to timer function and you are changing value of local variable of timer.

a = 100;
var i = setInterval( timer, 1000 );

function timer() {
    console.log( a );
    if ( a < 1 ) {
        console.log( 'Reaching Stop' ); 
        clearInterval( i );
        return;         
    } 
    a -= 1;
}
Sign up to request clarification or add additional context in comments.

Comments

2

When you pass the variable as a parameter to a function, you create a closure, which creates new scope for the variable.

Since the variable is global, you don't need to pass it in:

http://jsfiddle.net/FBVTT/

var a = 100;
var i = setInterval(timer, 1000);

function timer() {
    console.log(a);
    if (a < 1) {
        console.log('Reaching Stop');
        clearInterval(i);
        return;
    }
    a -= 1;
}

Here's an MDN page on closures.

2 Comments

Yup,its working and im more confused now ...lol ,if i pass it as a variable ,does it become a different variable then ?
Yes, it has a different scope. It's not like reference types in c#, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.