3

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

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

So with this I don't even need the Inc function?
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.