-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStopwatch.js
More file actions
42 lines (37 loc) · 1.12 KB
/
Copy pathStopwatch.js
File metadata and controls
42 lines (37 loc) · 1.12 KB
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
class Stopwatch {
constructor() {
this.startTime = 0;
this.elapsedTime = 0;
this.running = false;
this.interval = null;
}
start() {
if (!this.running) {
this.startTime = Date.now() - this.elapsedTime;
this.interval = setInterval(() => {
this.elapsedTime = Date.now() - this.startTime;
this.display();
}, 100);
this.running = true;
}
}
stop() {
if (this.running) {
clearInterval(this.interval);
this.running = false;
}
}
reset() {
this.stop();
this.elapsedTime = 0;
this.display();
}
display() {
const time = new Date(this.elapsedTime);
const minutes = String(time.getUTCMinutes()).padStart(2, '0');
const seconds = String(time.getUTCSeconds()).padStart(2, '0');
const milliseconds = String(time.getUTCMilliseconds()).padStart(3, '0').slice(0, 2);
document.getElementById('stopwatch-display').innerText = `${minutes}:${seconds}.${milliseconds}`;
}
}
export default Stopwatch;