luppi
luppi

Reputation: 301

Javascript pass variable by reference

How can I pass variables by reference to setInterval's call back function?
I don't want to define a 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();

Upvotes: 3

Views: 694

Answers (1)

David Hedlund
David Hedlund

Reputation: 129832

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();

Upvotes: 4

Related Questions