Register now and start sharing your code snippets.
-->
Simple JavaScript countdown timer
JavaScript posted about 1 month ago by christian
This JavaScript displays the days, hours, minutes and seconds left to the given date:
1 function Countdown(then) { 2 3 this.then = then; 4 5 function setElement(id, value) { 6 if (value.length < 2) { 7 value = "0" + value; 8 } 9 10 window.document.getElementById(id).innerHTML = value; 11 } 12 13 function countdown() { 14 now = new Date(); 15 diff = new Date(this.then - now); 16 17 seconds_left = Math.floor(diff.valueOf() / 1000); 18 19 seconds = Math.floor(seconds_left / 1) % 60; 20 minutes = Math.floor(seconds_left / 60) % 60; 21 hours = Math.floor(seconds_left / 3600) % 24; 22 days = Math.floor(seconds_left / 86400) % 86400; 23 24 setElement('countdown-days', days); 25 setElement('countdown-hours', hours); 26 setElement('countdown-minutes', minutes); 27 setElement('countdown-seconds', seconds); 28 29 countdown.timer = setTimeout(countdown, 1000); 30 } 31 32 33 function start() { 34 this.timer = setTimeout(countdown, 1000); 35 } 36 37 start(then); 38 } 39 40 Countdown(new Date("Dec 04 2008 12:00:00"));
Required HTML:
1 <span id="countdown-days"></span> days 2 3 <span id="countdown-hours"></span>:<span id="countdown-minutes"></span>:<span id="countdown-seconds"></span>
Output is for example:
1 23 days 23:00:12