I wrote the following script for a countdown clock. My goal was to dynamically create HTMLElement (span) and update innerHTML using window.setInterval. However, I am facing an issue with updating the current date without creating a new group of spans.
Here is my code:
var CustomCountdown;
(function (CustomCountdown) {
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;
};
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 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];
}
}
};
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);
};
return Countdown;
})();
CustomCountdown.Countdown = Countdown;
})(CustomCountdown || (CustomCountdown = {}));