Countdown timer in Javascript


Below is the code to create a timer till a specific datetime.

For this sample, the deadline is 5/16/2021 11:26:00

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript">

     function getTimeRemaining(endtime) {
      var d = new Date();
      var t = endtime.getTime() - d.getTime(); 

      var seconds = Math.floor((t / 1000) % 60);
      var minutes = Math.floor((t / 1000 / 60) % 60);
      var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
      var days = Math.floor(t / (1000 * 60 * 60 * 24));
      return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
      };
     }

   function initializeCountdown(id, endtime) {
    var clock = document.getElementById(id); 
    var daysSpan = clock.querySelector('.days');
    var hoursSpan = clock.querySelector('.hours');
    var minutesSpan = clock.querySelector('.minutes');
    var secondsSpan = clock.querySelector('.seconds');

   function updateTimer() {
        var t = getTimeRemaining(endtime);
       
        daysSpan.innerHTML = t.days;
        hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
        minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
        secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

        if (t.total <= 0) {
            clearInterval(timeinterval);
        }
     }
     updateTimer();

     var timeinterval = setInterval(updateTimer, 1000);
    }

    window.onload = function () {
     var deadline = new Date("5/16/2021 11:26:00"); // The datetime of the 
     deadline
     initializeCountdown('clockdiv', deadline);
  }
</script>
</head>

<body>
<form id="form1" runat="server">
   
<div id="clockdiv">
  <div style="float:left;">
    <span class="days"></span>
    <div>Days</div>
  </div>
  <div style="float:left;">
    <span class="hours"></span>
    <div>Hours</div>
  </div>
  <div style="float:left;">
    <span class="minutes"></span>
    <div>Minutes</div>
  </div>
  <div style="float:left;">
    <span class="seconds"></span>
    <div>Seconds</div>
  </div>
</div>
</form>
</body>
</html>

Output –

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.