JSFiddle - React, Tailwind, and code Playground
JavaScript
var CountdownClock;
(function(CountdownClock) {
var Countdown = (function() {
function Countdown(id, endDate, message) {
this.id = id;
this.endDate = endDate;
this.message = message;
}
Countdown.appendChildElement = function(DOMNode, tagName) {
var child = document.createElement(tagName);
DOMNode.appendChild(child);
return child;
};
/* Add a method to remove the old span*/
Countdown.prototype.removeSpan = function(){
if(this.span){
this.span.remove();
}
};
Countdown.prototype.getTimeRemaining = function(enddate) {
var t = Date.parse(enddate) - Date.parse(new Date().toString());
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
};
};
Countdown.prototype.drawCountdown = function(id, enddate) {
var self = this;
var container = document.getElementById(id);
var timeRemaining = this.getTimeRemaining(enddate);
var update = function() {
for (var key in timeRemaining) {
if (timeRemaining.hasOwnProperty(key)) {
var span = Countdown.appendChildElement(container, 'span');
span.setAttribute('class', key);
span.innerHTML = timeRemaining[key];
self.removeSpan(); //Remove the old span
self.span = span; //Set the new span
}
}
};
return update();
};
Countdown.prototype.initialize = function() {
var that = this;
this.drawCountdown(that.id, that.endDate);
var update = setInterval((function() {
that.drawCountdown(that.id, that.endDate);
}), 1000);
// var updateCountdown = setInterval(
// ...