forked from eromatiya/squareup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclock.js
64 lines (56 loc) · 1.46 KB
/
clock.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
class Clock {
constructor() {
this._localStorage = window.localStorage;
this._clock = document.querySelector('#clock');
this._setTime = this._setTime.bind(this);
this._twentyFourMode = false;
this._clockUpdater = null;
this._init();
}
_appendZero(k) {
// Append zero if k < 10
return k = (k < 10) ? '0' + k : k;
}
_setTime() {
const date = new Date();
let hour = date.getHours();
let min = date.getMinutes();
let midDay = null;
min = this._appendZero(min);
// 24-hour mode
if (this._twentyFourMode === true) {
hour = this._appendZero(hour);
this._clock.innerText = `${hour}:${min}`;
return;
}
// 12-hour mode
midDay = (hour >= 12) ? 'PM' : 'AM';
hour = (hour === 0) ? 12 : ((hour > 12) ? (hour - 12) : hour);
hour = this._appendZero(hour);
this._clock.innerText = `${hour}:${min} ${midDay}`;
}
_startClock() {
this._setTime();
this._clockUpdater = setInterval(this._setTime, 1000);
}
_updateClockMode() {
clearInterval(this._clockUpdater);
this._twentyFourMode = !this._twentyFourMode;
this._localStorage.setItem('twentyFourMode', JSON.stringify(this._twentyFourMode));
this._startClock();
}
_clockClickEvent() {
this._clock.addEventListener(
'click',
() => {
console.log('toggle 24-hour clock mode');
this._updateClockMode();
}
);
}
_init() {
this._twentyFourMode = JSON.parse(this._localStorage.getItem('twentyFourMode')) || false;
this._startClock();
this._clockClickEvent();
}
}