-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
73 lines (62 loc) · 1.97 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
class Stopwatch {
constructor() {
this.startTime = null;
this.elapsedTime = 0;
this.timerInterval = null;
}
start() {
if (!this.startTime) {
this.startTime = new Date().getTime();
this.timerInterval = setInterval(() => {
const currentTime = new Date().getTime();
this.elapsedTime += currentTime - this.startTime;
this.startTime = currentTime;
this.updateDisplay();
}, 1000);
}
}
stop() {
if (this.startTime) {
clearInterval(this.timerInterval);
this.startTime = null;
}
}
reset() {
this.elapsedTime = 0;
this.updateDisplay();
}
updateDisplay() {
const seconds = Math.floor(this.elapsedTime / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const formattedTime = formatTime(hours, minutes % 60, seconds % 60);
document.getElementById("time").textContent = formattedTime;
}
}
function formatTime(hours, minutes, seconds) {
return `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
}
function padZero(number) {
return number.toString().padStart(2, "0");
}
function startStopwatch(stopwatch) {
const startStopButton = document.getElementById("startStopButton");
if (startStopButton.textContent === "Start") {
startStopButton.textContent = "Stop";
stopwatch.start();
} else {
startStopButton.textContent = "Start";
stopwatch.stop();
}
}
function resetStopwatch(stopwatch) {
stopwatch.reset();
document.getElementById("startStopButton").textContent = "Start";
}
const stopwatch = new Stopwatch();
document.getElementById("startStopButton").addEventListener("click", () => {
startStopwatch(stopwatch);
});
document.getElementById("resetButton").addEventListener("click", () => {
resetStopwatch(stopwatch);
});