Skip to content

Client side Countdown Timer

kdaisho edited this page Dec 18, 2017 · 17 revisions

How to build global countdown timer using JavaScript

If you are asked to build a countdown timer but you don't have access to server-side language.

"use strict"; var deadline = "Wed, 29 June 2016 18:30:00 GMT-04: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; 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); clock.innerHTML = '<table>' + '<tr class="days">' + '<td colspan="2">' + days +'</td><td>days</td>' + '</tr>' + '<tr class="hours">' + '<td>' + hours + ':</td><td>' + minutes + ':</td><td>' + seconds + '</td>' + '</tr>' + '<tr class="units">' + '<td>hrs</td><td>min</td><td>sec</td>' + '</tr>' + '</table>'; if (remain <= 1000) { clearInterval(timeinterval); } }, 1000); } countdown('timer', deadline);

Clone this wiki locally