-
Notifications
You must be signed in to change notification settings - Fork 0
Client side Countdown Timer
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.
<div id="timer"></div>
"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);
- Pros: You can implement only in HTML and JavaScript.
- Cons: This timer relies on client's system time as it is written in JS. That means if client's system time is set wrong, timer displays wrong remaining hours. But imagine how many of computers always connected to internet have wrong system time? Look at your phone.
Note: html table is used in the example above but there's no need for you to do the same at all. The reason behind is almost all font types have letters with unique width and it makes displayed hours (especially seconds) TWITCH every second. To prevent that you need to give enough space between digits or use table like the example above so that character width won't affect whole layout.