-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
88 lines (70 loc) · 1.86 KB
/
app.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
;(function() {
'use strict'
//
// Variables
//
const app = document.querySelector('#app')
const data = {
timer: 120
}
let count = data.timer
//
// Methods
//
/**
* String.prototype.padStart() polyfill
* https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
*/
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0 //truncate if number or convert non-number to 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ')
if (this.length > targetLength) {
return String(this)
} else {
targetLength = targetLength - this.length
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length) //append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(this)
}
}
}
const formatTimer = count => {
const minutes = parseInt(count / 60, 10)
const seconds = count % 60
const paddedMinutes = minutes.toString()
const paddedSeconds = seconds.toString().padStart(2, '0')
return paddedMinutes + ':' + paddedSeconds
}
const template = _ => {
if (count === 0) {
return '<p>⏰</p><button id="restart">Restart Timer</button>'
}
return `<p>${formatTimer(count)}</p>`
}
const render = _ => {
app.innerHTML = template()
}
const startTimer = _ => {
const countdown = setInterval(function() {
render()
count--
if (count < 0) {
clearInterval(countdown)
}
}, 1000)
}
const restartTimer = _ => {
if (event.target.id === 'restart') {
count = data.timer
startTimer()
}
}
//
// Inits & Event Listeners
//
startTimer()
document.addEventListener('click', restartTimer, false)
})()