Countdown Timer - formatted
<div id="app"></div>
<script>
var duration = 5;
var timer;
var Rue = function (selector, options) {
this.elem = document.querySelector(selector);
this.data = options.data;
this.template = options.template;
};
Rue.prototype.render = function () {
this.elem.innerHTML = this.template(this.data);
};
var stopTimer = function () {
if (app.data.time > 0) return;
clearInterval(timer);
};
var startTimer = function () {
app.data.time = duration;
app.render();
timer = setInterval(countdown, 1000);
};
var countdown = function () {
app.data.time--;
stopTimer();
app.render();
};
var clickHandler = function (event) {
if (!event.target.hasAttribute('data-restart-timer')) return;
startTimer();
};
var app = new Rue('#app', {
data: {
time: duration
},
template: function (props) {
if (props.time < 1) {
return '⏰ <p><button data-restart-timer>Restart Timer</button></p>';
}
return getTimerHTML(props);
}
});
var getTimerHTML = function (props) {
var minutes = parseInt(props.time / 60, 10);
var seconds = props.time % 60;
return minutes.toString() + ':' + seconds.toString().padStart(2, '0');
}
startTimer();
document.addEventListener('click', clickHandler);
</script>