JSFiddle - React, Tailwind, and code Playground
HTML
<div id="odpocet" data-datum="2014-01-27 10:00"></div>
JavaScript
var Countdown = function (el) {
this.element = el,
this.timer = null,
this.deadline = new Date($(el).data("datum")),
this.remainingDays = remainingHours = remainingMins = remainingSecs = 0;
};
Countdown.prototype.update = function () {
var seconds = (this.deadline.getTime() - new Date().getTime()) / 1000;
this.remainingDays = Math.floor(seconds / 86400); // 86400000
this.remainingHours = Math.floor(seconds % 86400 / 3600); // 3600000
this.remainingMins = Math.floor(seconds % 3600 / 60); // 60000
this.remainingSecs = Math.floor(seconds % 60); //1000
//this.mil = Math.floor(seconds * 10 % 10);
};
Countdown.prototype.render = function () {
var text = "";
text += this.remainingDays > 0 ? (this.remainingDays + " d ") : "";
text += this.remainingHours > 0 ? (this.remainingHours + " hod ") : "";
text += this.remainingMins > 0 ? (this.remainingMins + " min ") : "";
text += this.remainingSecs > 0 ? (this.remainingSecs + " sec ") : "";
$(this.element).html("<span>" + text + "</span>");
};
Countdown.prototype.start = function() {
this.timer = setInterval(function (_this) {
_this.update();
_this.render();
}, 100, this);
};
Countdown.prototype.stop = function() {
clearInterval(this.timer);
};
var countdowns = new Array();
function Initialize(){
var elements = $("#odpocet");
for (var i = 0; i < elements.length; i++) {
countdowns[i] = new Countdown(elements[i]);
countdowns[i].start();
}
}
Initialize();