access variable within setInterval

Asked

Viewed 113 times

0

Good morning, I’m trying to find out how to access a declared attribute in a setInterval/setTimeOut function in another function. With the little study I have on Javascript, a variable declared in local scope cannot be accessed in another local scope (a function accessing attributes of another) unless it is this.variavel because it makes it "publish" and you instate an object of that variable in the other function obj = new NomeDaFuncao(). Unfortunately I don’t know how to instantiate an object of a setInterval/setTimeOut function. Below is the 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);
    }

  • Explain better what you want to achieve with this because the code is very confusing.

  • is a long story... pretend you only have a variable=10 there in setInterval kkkk

  • is why this button .remove-button is added dynamically, it is not in the html page yet, so I put this loop there to select it when it is generated '-'

  • Use this only makes sense if you are working within an object / class definition. Otherwise, this will point to the window and you’ll end up creating a global variable - which may even solve your problem, but it’s a bad idea.

1 answer

1

We can not say what would be the best solution in its context, because we do not know more details of the code. But one possibility is to take advantage of the functioning of closures. In summary, define the variable in the external 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.