Return value SetInterval

1

How can I return a value from a setInterval?

result = setInterval(function () {
   var cont = i++;
   return cont;
}, 800);
    
asked by anonymous 27.05.2016 / 11:11

3 answers

2

You need to use asynchronous logic with callbacks .

When you do

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

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

Then it will have 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);
    
27.05.2016 / 12:26
3

The function setInterval returns an interval id (used to later cancel this interval), 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 the 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
    
27.05.2016 / 11:37
2

You will need to declare the variable cont as global variable, since the value that the function takes is the ID of the range ...

i=0;
var cont=0;
setInterval(function () {
   cont = i++;
}, 800);
    
27.05.2016 / 11:24