I have a page where I want show multiple countdowns. I made a javascript code that makes the countdown and it works on all divs that i specify, but this goes in real time only on the last div. Can someone help me? I posted the page below.
<html>
<head>
<title>Timer</title>
<head>
<script type="text/javascript">
function Timer(){
this.countdown=function(fineanno, finemese, finegiorno, fineore, fineminuti, finesecondi, nomediv)
{
var_div=nomediv;
var_anno=fineanno;
var_mese=finemese;
var_giorno=finegiorno;
var_ore=fineore;
var_minuti=fineminuti;
var_secondi=finesecondi;
data_scandeza= new Date(var_anno,var_mese-1,var_giorno,var_ore,var_minuti,var_secondi);
data_oggi= new Date();
differenza=(data_scandeza-data_oggi);
giorni=parseInt(differenza/86400000);
differenza=differenza-(giorni*86400000);
ore=parseInt(differenza/3600000);
differenza=differenza-(ore*3600000);
minuti=parseInt(differenza/60000);
differenza=differenza-(minuti*60000);
secondi=parseInt(differenza/1000);
differenza=differenza-(secondi*1000);
if (giorni <= "0" && ore <= "0" && minuti <= "0" && secondi <= "0")
{
document.getElementById(nomediv).innerHTML="Tempo scaduto";
}
else
{
document.getElementById(nomediv).innerHTML=giorni +' giorni '+ore+' ore '+minuti+' min '+secondi+' sec';
setTimeout("t"+var_div+".countdown(var_anno, var_mese, var_giorno, var_ore, var_minuti, var_secondi, var_div)",1000);
}
}
}
</script>
</head>
<body>
<div id="div2"></div>
<script>
var tdiv2 = new Timer();
tdiv2.countdown("2013","04","26", "23","00","00","div2");
</script>
<div id="div3"></div>
<script>
var tdiv3 = new Timer();
tdiv3.countdown("2013","04","26", "23","00","00","div3");
</script>
</body>
</html>
var_div
, var_anno
, var_mese
, var_giorno
, var_ore
, var_minuti
and var_secondi
are global variables, because you declared them without using the var
keyword. That means all your calls to countdown
will access the same variable.
Don't use the name of the variable in your setTimeout
, or you'll get the current value of this global variable (the second one set). Instead, use the value of the variable at the time you build the settimeout, like this:
setTimeout("t"+var_div+".countdown(" + var_anno + ", " + var_mese + ", " + var_giorno + ", " + var_ore + ", " + var_minuti + ", " + var_secondi + ",'" + var_div + "')",1000);
In fact I don't see any need for this part at all:
var_div=nomediv;
var_anno=fineanno;
var_mese=finemese;
var_giorno=finegiorno;
var_ore=fineore;
var_minuti=fineminuti;
var_secondi=finesecondi;
Instead of using those new variables, you can just use the parameters that were passed in. I suppose the reason you had that is so the setTimeout
would have a variable to read the value from, but with my suggested change above it is no longer necessary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.