Countdown Timer - start and pause
<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 () {
clearInterval(timer);
};
var countdown = function () {
app.data.time--;
if (app.data.time < 1) {
stopTimer();
}
app.render();
};
var clickHandler = function (event) {
startTimer(event);
pauseTimer(event);
restartTimer(event);
};
var startTimer = function (event) {
if (!event.target.hasAttribute('data-start-timer')) return;
if (app.data.time < 1) {
restartTimer();
return;
}
app.data.paused = false;
app.render();
timer = setInterval(countdown, 1000);
};
var pauseTimer = function (event) {
if (!event.target.hasAttribute('data-pause-timer')) return;
stopTimer();
app.data.paused = true;
app.render();
};
var restartTimer = function (event) {
if (!event.target.hasAttribute('data-restart-timer')) return;
stopTimer();
app.data.time = duration;
app.data.paused = false;
app.render();
timer = setInterval(countdown, 1000);
};
var app = new Rue('#app', {
data: {
time: duration,
paused: true
},
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;
var html =
minutes.toString() + ':' + seconds.toString().padStart(2, '0') +
'<p>' +
(props.paused ? '<button data-start-timer>Start</button>' : '<button data-pause-timer>Pause</button>') +
' <button data-restart-timer>Restart</button>' +
'</p>';
return html;
}
app.render();
document.addEventListener('click', clickHandler);
</script>