Javascript pass variable by reference

How to pass variables by reference to setInterval callback function?
I do not 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();
+3
source share
1 answer

If you create a closure for it, you don’t have to pass the value at all, it will be available only in the inner area, but not outside the function Test:

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();
+4
source

Source: https://habr.com/ru/post/1731211/


All Articles