Joseph Michael Pesch
VP Programming

Javascript Countdown Timer Example

by 7. August 2009 15:47

<html>
<head>

<style type="text/css">
  body { font-size: .85em; }
  body,input,div { font-family: tahoma, verdana, arial; }
  div.Countdown { background-color: #fafad2; width: 450px; }
  #content { width: 475px; margin-left: auto; margin-right: auto; text-align: center; }
</style>

<script id="CountdownScript" type="text/javascript">
  function SetDefaultEnd() {
    var dt = new Date();
    var tm = dt.getTime();
    tm += 3600 * 1000 * 48;
    dt.setTime(tm);
    document.getElementById('txtEnd').value = dt;
  }
  function StartCountdown() {
    if (document.getElementById('txtTimer').innerHTML == 'Time is up')
      return;
    var expiry = new Date(document.getElementById('txtEnd').value);
    setTimeout('Countdown(' + expiry.getTime() + ')', 1000);
  }
  function Countdown(end) {
    var now = new Date();
    var span = (end - now.getTime()) / 1000;
    if (span <= 0) {
      // Countdown finished...
      document.getElementById('txtTimer').innerHTML = 'Time is up';
      return;
    }
    var days = Math.floor(span / 86400)
    var hours = Math.floor(span % 86400 / 3600);
    var mins = Math.floor(span % 86400 % 3600 / 60);
    var secs = Math.floor(span % 86400 % 3600 % 60);
    var d = (((parseInt(days) > 0) ? days + ' day' + ((parseInt(days) != 1) ? 's ' : ' ') : ''));
    var h = (((parseInt(hours) > 0) ? hours + ' hour' + ((parseInt(hours) != 1) ? 's ' : ' ') : ''));
    var m = mins + ' minutes ';
    var s = secs + ' seconds ';
    msg = 'Time is up in: ' + d + h + m + s;
    document.getElementById('txtTimer').innerHTML = msg;
    setTimeout('Countdown(' + end + ')', 1000);
  }
</script>


</head>

<body onload="SetDefaultEnd();">

<div id="content">
  Enter End Date:
  <input type="text" id="txtEnd" style="width: 200px; text-align: center;"" />
  <input type="button" id="btnStart" onclick="StartCountdown();" value="Start Countdown" />
  <div class="Countdown" id="txtTimer"></div>
</div>

</body>
</html>

Tags: ,

[None]

Comments are closed