Return setInterval Value

Asked

Viewed 331 times

1

How can I return a setInterval value ?

result = setInterval(function () {
   var cont = i++;
   return cont;
}, 800);

3 answers

3

The function setInterval returns an id of the range (used to later cancel this range), so you should not use return.

You can use scopes but according to Pedro Luzio’s answer. Additionally you can use a IIFE to delimit the scope of variables.

var cont=0; // visivel em escopo "global"
(function(){
    var i=0; // visivel somente dentro do bloco
    setInterval(function () {
        cont = i++;
    }, 800);
})();

// alert(cont) funciona
/// alert(i) undefined

2

You have to declare the cont variable as the global variable, because the value that the function takes is the range ID...

i=0;
var cont=0;
setInterval(function () {
   cont = i++;
}, 800);

2


You have to use an asynchronous logic with callbacks.

When you do

var result = setInterval(function () {
   var cont = i++;
   return cont;
}, 800);

result saves an instance of the setInterval itself so that you can stop or cancel. But to know the value of cont, or better to use it in code you have to call another function passing it the value that cont has at the time the setInterval is run. That is, chain the code to the next step be called at the time the setInterval is running its function.

So it has to be something like:

function proximaFuncao(contagem){
    // aqui podes usar a variável "contagem" que irá ter o valor que "cont" tem no momento que esta função é invocada
}

var result = setInterval(function () {
   var cont = i++;
   proximaFuncao(cont);
}, 800);
  • I just don’t quite understand why it is i in this context, it is not specified in the question. If the goal is only the counter or i need to be there. It wasn’t explained to us what it was for

  • @Miguel well, I didn’t, but I didn’t change to just change what has to do with asynchronous logic. But I think the problem is the asynchrony.

  • 1

    Yap. Good solution there

Browser other questions tagged

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