On a page I have several countdowns and when they reach zero I want the function to stop, but I can't.
This is the code:
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";
clearInterval(stop);
}
}
for(var i=0;i<a.length;i++)
{
(function(i)
{
var stop = setInterval(function(){mifun(a[i]);}, 1000);
})(i);
}
<span id=demo4></span><br>
<span id=demo5></span><br>
<span id=demo6></span><br>
It works, but after displaying the Account Terminated message, that message keeps painting you over and over again indefinitely.
If I take the following line out of the loop for
:
var stop = setInterval(function(){mifun(a[0]);}, 1000);
And I do a test with the zero element of the array, so the function stops setinterval()
, but I need it to be inside a for
, since the countdowns can vary and be more or less.
How can I make the calls to the function stop?
This way I don't have to save the value returned by setInterval()
This code works correctly to display the first countdown
var a = [];
var b = {segundos: 5, elemento: 'demo1'};
a.push(b);
b = {segundos: 7, elemento: 'demo2'};
a.push(b);
var i=0;
function MiFuncionJS()
{
if(a[i].segundos>0)
{
document.getElementById(a[i].elemento).innerHTML = a[i].segundos;
a[i].segundos--;
setTimeout("MiFuncionJS()", 1000);
}
else
document.getElementById(a[i].elemento).innerHTML = "Cuenta finalizada";
}
MiFuncionJS();
<span id="demo1"></span><br>
<span id="demo2"></span><br>
The countdown works and MyJSFunction() is no longer called when the countdown ends
But when I want to show several accounts it fails me, then I put the code
var a = [];
var b = {segundos: 5, elemento: 'demo1'};
a.push(b);
b = {segundos: 7, elemento: 'demo2'};
a.push(b);
for(var i=0;i<a.length;i++)
{
(function(i)
{
function MiFuncionJS()
{
if(a[i].segundos>0)
{
document.getElementById(a[i].elemento).innerHTML = a[i].segundos;
a[i].segundos--;
setTimeout("MiFuncionJS()", 1000);
}
else
document.getElementById(a[i].elemento).innerHTML = "Cuenta finalizada";
}
MiFuncionJS();
})(i);
}
<span id="demo1"></span><br>
<span id="demo2"></span><br>
It only displays the data once...
In your code you are overwriting the value of the variable
stop
with the output oversetInterval()
and over again, so at the end of the loopstop
it will keep the last value and the previous ones will have been lost, so they willclearInterval(stop);
always be stopped by the last counter.You need the following modifications to your code to keep the return value of each call to
setInterval()
be able to use it in your function call:I recommend the following way to work around your problem elegantly by keeping the countdown in the element's own data attributes
<span>
:This is how I solved it too...
Or using forEach instead of for...