variable access within setInterval

0

Good morning, I'm trying to know how to access an attribute declared in a setInterval / setTimeOut function in another function. With the little bit of study I have on JavaScript, a variable declared in local scope can not be accessed in another local site (a function accessing attributes of another) unless it is this.variavel because it makes it "public" and you instantiate a object of this variable in the other obj = new NomeDaFuncao() function. Unfortunately I'm not sure how to instantiate an object from a setInterval / setTimeOut function. Below is an example of what I'm trying to do.

setInterval(() =>
    {
        this.btn = document.querySelector(".remove-button");
    },0);
    
function FazAlgo()
    {
      btnRemove = new setInterval();
      console.log(btnRemove.btn.value);
    }
    
asked by anonymous 22.12.2017 / 14:34

1 answer

1

We can not tell you what would be the best solution in your context, because we do not know more details of the code. But one possibility is to take advantage of the functioning of the closures . In short, define the variable in the outer scope, and the functions of the more internal scopes will have access to it:

let minhaVar = 0;

setInterval(() => {
    minhaVar += 10;
},1000);
    
function fn() {
    console.log('valor da variável (a cada 2s)', minhaVar);
}

console.log('valor inicial da variável', minhaVar);
setInterval(fn, 2000);
    
22.12.2017 / 14:49