-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
122 lines (99 loc) · 2.32 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
modes = Object.freeze({
WORK: 0,
BREAK: 1
});
class Timer {
constructor() {
this.worktimeLength = 1500;
this.breaktimeLength = 300;
this.mode = modes.WORK;
this._timeRemaining = 1500;
this._paused = true;
this._message = 'Start';
this.timeUpdated = () => {};
this.messageUpdated = () => {};
}
get timeRemaining() {
return this._timeRemaining;
}
set timeRemaining(time) {
this._timeRemaining = time;
this.timeUpdated();
}
get message() {
return this._message;
}
set message(message) {
this._message = message;
this.messageUpdated();
}
reset() {
this.timeRemaining = this.worktimeLength;
this.mode = modes.WORK;
}
start() {
if (!this._paused) return;
this._paused = false;
this.message = 'Pause';
this.countdown = setInterval(() => {
this.timeRemaining = this.timeRemaining - 1;
if (this.timeRemaining <= 0) {
clearInterval(this.countdown);
}
}, 1000);
}
pause() {
if (this._paused) return;
this._paused = true;
clearInterval(this.countdown);
this.message = 'Start'
}
togglePause() {
if (this._paused) {
this.start();
} else {
this.pause();
}
}
switchMode() {
this.mode = this.mode === modes.WORK ? modes.BREAK : modes.WORK;
}
}
Number.prototype.pad = function (size = 2) {
let s = String(this);
while (s.length < size) {
s = '0' + s;
}
return s;
}
function formatDisplay(seconds) {
const minutes = Math.trunc(seconds / 60);
seconds = seconds % 60;
return `${minutes.pad()}:${seconds.pad()}`;
}
// Node-only code
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = {
formatDisplay,
Timer,
modes
};
} else { // Browser-only code
function timerClick() {
timer.togglePause();
}
// Wire up to the DOM
const timerDiv = document.querySelector('#timer');
const time = document.querySelector('#time');
const message = document.querySelector('#message');
const timer = new Timer();
function updateTime() {
time.textContent = formatDisplay(timer.timeRemaining);
}
timer.timeUpdated = updateTime;
function updateMessage() {
message.textContent = timer.message;
}
timer.messageUpdated = updateMessage;
timerDiv.addEventListener('click', timerClick);
}