30. Countdown Timer - Formatted

HTML

1
<div id="app" aria-live="polite"></div>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* Before rendering the time into the UI, convert it into M:SS format. For example, the starting time should be displayed at 2:00. When the remaining time is 5 seconds, it should be displayed as 0:05. */

const timeValue = 120;
const 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);
};
Rue.prototype.restartTimer = function () {
this.data.time = timeValue;
app.timer()
}
Rue.prototype.stopTimer = function () {
this.elem.innerHTML = `<h2>It's over, start again:</h2><button onclick="app.restartTimer()" class="button">Start Again</button>`
}
Rue.prototype.timer = function () {
const intervalCount = window.setInterval(function () {
if(!app) return;
app.data.time--
app.render();
if (app.data.time < 1) {
window.clearInterval(intervalCount)
app.stopTimer()
}
}, 1000);
app.render();
};
Rue.prototype.formatTime = function (time) {
let minutes = Math.floor(time / 60);
let seconds = time % 60;
return `${(minutes.toString().padStart(2,'0'))}:${seconds.toString().padStart(2,'0')}`;
}
const app = new Rue('#app', {
data: {
time: timeValue,
},
template: function (props) {
if (!props) return;
let html = `<h2>You've got only <span class="counter">${app.formatTime(props.time)}</span> seconds!</h2>`;
return html;
}
})
app.timer();