Here’s a simple one I came up with. It does a countdown until a certain date. Quite simple.
Hope you can find use for it:
var CDOWN = {
init : function()
{
this.dformat = "[D]:[H]:[M]:[S]"; // Day:Hour:Minute:Second - Any can be removed
this.tdate = "11/19/2008 6:00 PM"; // Until when to countdown (MM/DD/YYYY)
this.count = true; // Update the counter each second or minute or whatever is defined above
this.endstr = "Live now!"; // To display once the countdown is complete
this.lzero = true; // Display leading zeros on numbers lower than 10
this.counts = -1;
this.counts = Math.ceil(this.counts);
if(this.counts == 0)
this.count = false;
this.timeoutp = (Math.abs(this.counts)-1)*1000 + 990;
dthen = new Date(this.tdate);
dnow = new Date();
ddiff = (this.counts > 0) ? new Date(dnow-dthen) : new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CDOWN.startCounter(gsecs);
},
calculate : function(secs, num1, num2)
{
s = ((Math.floor(secs/num1))%num2).toString();
if(this.lzero && s.length < 2)
s = "0" + s;
return s;
},
startCounter : function(secs)
{
if(secs < 0)
{
document.getElementById("timer").innerHTML = this.endstr;
return;
}
this.dsp = this.dformat.replace(/\[D\]/g, CDOWN.calculate(secs,86400,100000));
this.dsp = this.dsp.replace(/\[H\]/g, CDOWN.calculate(secs,3600,24));
this.dsp = this.dsp.replace(/\[M\]/g, CDOWN.calculate(secs,60,60));
this.dsp = this.dsp.replace(/\[S\]/g, CDOWN.calculate(secs,1,60));
document.getElementById('timer').innerHTML = this.dsp;
if(this.count)
setTimeout("CDOWN.startCounter(" + (secs+this.counts) + ")", this.timeoutp);
}
}
/* LOAD */
function addLoadEvent(fn)
{
var old = window.onload;
if(typeof window.onload != 'function')
window.onload = fn;
else
window.onload = function()
{
old();
fn();
}
}
addLoadEvent(function() { CDOWN.init(); });
In order to display this inside some container, you will need to define one and set it’s ID to be the same as in the script. For example:
document.getElementById('timer').innerHTML = this.dsp;
In this case my container’s id is “timer” and the actual countdown will be displayed there.
¡Gracias por el código! ¡Qué buen sitio!
De nada, me alegro que te haya sido de utilidad. Un saludo.
Just noticed a small bug in the code, not really the code but how it was displayed, also removed one unnecessary if statement.