I need to display multiple countdowns at once. The data will be taken from a database and may be a single account or more than one. Here is an example:
//var a = [4, 5, 6];
var a=[];
var b={};
for(var i=3;i<6;i++)
{
b = {segundos: (i+1), elemento: 'demo' + (i+1)};
a.push(b);
}
function mifun(X)
{
if(X.segundos>0)
{
document.getElementById(X.elemento).innerHTML = X.segundos;
X.segundos--;
}
else document.getElementById(X.elemento).innerHTML = "Cuenta finalizada";
}
setInterval(function(){mifun(a[0]);},1000);
setInterval(function(){mifun(a[1]);},1000);
setInterval(function(){mifun(a[2]);},1000);
<span id=demo4></span><br>
<span id=demo5></span><br>
<span id=demo6></span>
This is a small example. The data is fetched in PHP and then passed to a vector in JavaScript. The size of the vector may vary depending on the information saved.
In this case I call the function setInterval
three times ( a[0]
, a[1]
and a[2]
). But the actual size of the vector will not always be the same. How could the setInterval function be called without having to write those last 3 lines?
I've tried putting it in a loop like the following but it doesn't work:
for(var i=0;i<a.length;i++)
setInterval(function(){mifun(a[i]);},1000);
The problem you have is that when you put it in a loop, the array is traversed with the index
i
, but when you callsetInterval
the value ofi
is no longer the same (the loop has moved), which will cause the accounts.A possible solution would be to change the definition of the variable, so that instead of being with
var
it is withlet
and the loop will work for you:With
let
is specifying that the scope of the variable is only in the block in which it is called (in your case, the loopfor
) and not the whole function, working as a closure, so you don't have the problem thati
it's not right defined after thefor
.If you don't want to use
let
because you want to give broader support to older browsers ( as Arnau Castellví suggests in the comments ), what you can do is create your own closure and keep usingvar
:Another solution is for your for loop to have a closure passed
i
to it, this will make iti
in the same context when it executes thesetInterval
.