Skip to content

Client side Countdown Timer

kdaisho edited this page Dec 30, 2017 · 17 revisions

How to build global countdown timer using JavaScript

One day your boss tells you to build a countdown timer for whatever promotions. Then she adds that the timer has to end AT THE SAME TIME across provinces. She doesn't that know the fact that you don't and won't have access to server-side languages. You're sick of explaining it over and over again.

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

Here's my solution.

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);

    // Inserting timer
    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);

I used html table in the example above but there's no need to use it at all. But some type of fonts have letters with different width and it makes numbers twitch every time it is inserted. To prevent this give enough space between numbers or use table like the example above.

Clone this wiki locally