-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstopwatch.js
42 lines (33 loc) · 1.31 KB
/
stopwatch.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
let startTime;
let stopwatchInterval;
let elapsedTime = 0;
function startStopwatch() {
startTime = Date.now() - elapsedTime;
stopwatchInterval = setInterval(updateStopwatch, 10);
}
function stopStopwatch() {
clearInterval(stopwatchInterval);
}
function resetStopwatch() {
clearInterval(stopwatchInterval);
elapsedTime = 0;
document.getElementById("timer").innerText = "00:00:000";
}
function updateStopwatch() {
const currentTime = Date.now();
elapsedTime = currentTime - startTime;
const formattedTime = formatTime(elapsedTime);
document.getElementById("timer").innerText = formattedTime;
}
function formatTime(timeInMilliseconds) {
const minutes = Math.floor(timeInMilliseconds / 60000);
const seconds = Math.floor((timeInMilliseconds % 60000) / 1000);
const milliseconds = Math.floor(((timeInMilliseconds % 60000) % 1000));
const formattedMinutes = padNumber(minutes);
const formattedSeconds = padNumber(seconds);
const formattedMilliseconds = padNumber(milliseconds);
return `${formattedMinutes}:${formattedSeconds}:${formattedMilliseconds}`;
}
function padNumber(number) {
return number.toString().padStart(2, "0");
}