the red penguin
HOME NEWS CONTACT ABOUT BLOG LOGIN

Javascript countdown timer

Here’s a nice compact version to display a countdown to a certain date and time on a webpage.

<span id="countdown" class="timer"></span>

<script>
var upgradeTime = 86401; // seconds remaining
var seconds = upgradeTime;
function timer() {
  var days        = Math.floor(seconds/24/60/60);
  var hoursLeft   = Math.floor((seconds) - (days*86400));
  var hours       = Math.floor(hoursLeft/3600);
  var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
  var minutes     = Math.floor(minutesLeft/60);
  var remainingSeconds = seconds % 60;
  function pad(n) {
    return (n < 10 ? "0" + n : n);
  }
  document.getElementById('countdown').innerHTML = pad(days) + "d:" + pad(hours) + "h:" + pad(minutes) + "m:" + pad(remainingSeconds) + "s";
  if (seconds <= 0) {
    clearInterval(countdownTimer);
    document.getElementById('countdown').innerHTML = "Completed";
  } else {
    seconds--;
  }
}
var countdownTimer = setInterval('timer()', 1000);
</script>
Tuesday 7 December 2021, 96 views


Leave a Reply

Your email address will not be published.