-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (46 loc) · 1.57 KB
/
index.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
const timerEl = document.getElementById("timer");
const startButtonEl = document.getElementById("start");
const stopButtonEl = document.getElementById("stop");
const resetButtonEl = document.getElementById("reset");
let startTime = 0;
let elapsedTime = 0;
let timerInterval;
function startTimer() {
startTime = Date.now() - elapsedTime;
timerInterval = setInterval(() => {
elapsedTime = Date.now() - startTime;
timerEl.textContent = formatTime(elapsedTime);
}, 10);
startButtonEl.disabled = true;
stopButtonEl.disabled = false;
}
function formatTime(elapsedTime) {
const milliseconds = Math.floor((elapsedTime % 1000) / 10);
const seconds = Math.floor((elapsedTime % (1000 * 60)) / 1000);
const minutes = Math.floor((elapsedTime % (1000 * 60 * 60)) / (1000 * 60));
const hours = Math.floor(elapsedTime / (1000 * 60 * 60));
return (
(hours ? (hours > 9 ? hours : "0" + hours) : "00") +
":" +
(minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" +
(seconds ? (seconds > 9 ? seconds : "0" + seconds) : "00") +
"." +
(milliseconds > 9 ? milliseconds : "0" + milliseconds)
);
}
function stopTimer() {
clearInterval(timerInterval);
startButtonEl.disabled = false;
stopButtonEl.disabled = true;
}
function resetTimer() {
clearInterval(timerInterval);
elapsedTime = 0;
timerEl.textContent = "00:00:00";
startButtonEl.disabled = false;
stopButtonEl.disabled = true;
}
startButtonEl.addEventListener("click", startTimer);
stopButtonEl.addEventListener("click", stopTimer);
resetButtonEl.addEventListener("click", resetTimer);