29. Countdown Timer

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
/* Use state-based UI to create the timer, and countdown from 60 seconds to 0 once a second. 
When the timer is done, stop the countdown and provide a way for users to start it again. */

const timeValue = 6;
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();
};
const app = new Rue('#app', {
data: {
time: timeValue,
},
template: function (props) {
if (!props) return;
let html = `<h2>You've got only <span class="counter">${props.time}</span> seconds!</h2>`;
return html;
}
})
app.timer();