tags:

views:

62

answers:

1

How can I pass variables by reference to setInetrav's call back function?
I don't want to define global variable just for the counter, is it possible?

    var intervalID;

    function Test(){
        var value = 50;               
        intervalID = setInterval(function(){Inc(value);}, 1000);              
    }

    function Inc(value){
        if (value > 100) 
            clearInterval(intervalID);
        value = value + 10;                                       
    }

    Test();
+3  A: 

If you create a closure for it, you won't have to pass the value at all, it'll just be available in the internal scope, but not outside the Test function:

function Test() {
    var value = 50;
    var intervalID = setInterval(function() {

        // we can still access 'value' and 'intervalID' here, altho they're not global
        if(value > 100)
            clearInterval(intervalID);

        value += 10;

    }, 1000);
}

Test();
David Hedlund
So with this I don't even need the Inc function?
luppi
in a way, you could say the `Inc` function is still there, but it's an *anonymous function* declared internally when it is being passed to `setInterval`
David Hedlund