Skip to content

Client side Countdown Timer

kdaisho edited this page Dec 18, 2017 · 17 revisions

How to build global countdown timer using JavaScript

One day your boss tells you to build a countdown timer for whatever stupid promotions. She doesn't know you don't have access to server-side language and you're sick of explaining it over and over again.

Besides Canada is multi-timezone country so how can you get it work the same way in different timezones using client-side language, eh?

Hope this saves you.

HTML

<div id="timer"></div>

JavaScript

"use strict";

//Set "GMT-04:00" during Daylight Saving Time (Mar - Nov)
var deadline = "Mon, 24 Dec 2018 00:00:00 GMT-05:00";

function getEndTime(endtime) {
  var t = Date.parse(endtime) - (new Date()).getTime();
  // var end = Date.parse(endtime);
  // var g_current = (new Date().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 {
    t: t,
    seconds: seconds,
    minutes: minutes,
    hours: hours,
    days: days
  };
}

function countdown(id, endtime) {
  var clock = document.getElementById(id);
  var timeinterval = setInterval(function() {
    var end = getEndTime(endtime);
    var remain = end.t;

    // Formatting number to have two digits with 0 prefixed
    var days = ("0" + end.days).slice(-2);
    var hours = ("0" + end.hours).slice(-2);
    var minutes = ("0" + end.minutes).slice(-2);
    var seconds = ("0" + end.seconds).slice(-2);

    // No need to use html table but some font-family have digits with different width. It makes numbers twitch every second.. So give enough space between numbers if you don't use table.
    clock.innerHTML = '<table>' +
                        '<tr>' +
                          '<td colspan="2">' + days +'</td><td>days</td>' +
                        '</tr>' +
                        '<tr>' +
                          '<td>' + hours + ':</td><td>' + minutes + ':</td><td>' + seconds + '</td>' +
                        '</tr>' +
                        '<tr>' +
                          '<td>H</td><td>M</td><td>S</td>' +
                        '</tr>' +
                      '</table>';
    if (remain <= 1000) {
      clearInterval(timeinterval);
    }
  }, 1000);
}
countdown('timer', deadline);
Clone this wiki locally