-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
48 lines (40 loc) · 1.15 KB
/
script.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
// Stopwatch program
const counter = document.getElementById("counter");
let timer = null;
let startTime = 0;
let elapsedTime = 0;
let isRunning = false;
function start() {
if (!isRunning) {
startTime = Date.now() - elapsedTime;
timer = setInterval(update, 10);
isRunning = true;
}
}
function stop() {
if (isRunning) {
clearInterval(timer);
elapsedTime = Date.now() - startTime;
isRunning = false;
}
}
function reset() {
clearInterval(timer);
startTime = 0;
elapsedTime = 0;
isRunning = false;
counter.textContent = `00:00:00:00`;
}
function update() {
const currentTime = Date.now();
elapsedTime = currentTime - startTime;
let hours = Math.floor(elapsedTime / (1000 * 60 * 60));
let minutes = Math.floor((elapsedTime / (1000 * 60)) % 60);
let seconds = Math.floor((elapsedTime / 1000) % 60);
let milliseconds = Math.floor((elapsedTime % 1000) / 10);
hours = String(hours).padStart(2, "0");
minutes = String(minutes).padStart(2, "0");
seconds = String(seconds).padStart(2, "0");
milliseconds = String(milliseconds).padStart(2, "0");
counter.textContent = `${hours}:${minutes}:${seconds}:${milliseconds}`;
}