-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
70 lines (61 loc) · 2.03 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const stopwatchDisplay = document.querySelector('.stopwatch');
const startButton = document.querySelector('.start');
const stopButton = document.querySelector('.stop');
const resetButton = document.querySelector('.reset');
const lapButton = document.querySelector('.lap');
const lapTimesList = document.querySelector('.lap-times');
let hours = 0;
let minutes = 0;
let seconds = 0;
let milliseconds = 0;
let interval;
let isRunning = false;
function displayTime() {
stopwatchDisplay.textContent = `${hours.toString().padStart(2, '0')} : ${minutes.toString().padStart(2, '0')} : ${seconds.toString().padStart(2, '0')} : ${milliseconds.toString().padStart(2, '0')}`;
}
function startStopwatch() {
isRunning = true;
interval = setInterval(function () {
milliseconds++;
if (milliseconds === 100) {
milliseconds = 0;
seconds++;
if (seconds === 60) {
seconds = 0;
minutes++;
if (minutes === 60) {
minutes = 0;
hours++;
}
}
}
displayTime();
}, 10);
}
function lapRecord() {
if (isRunning == true) {
const lapTime = `${hours.toString().padStart(2, '0')} : ${minutes.toString().padStart(2, '0')} : ${seconds.toString().padStart(2, '0')} : ${milliseconds.toString().padStart(2, '0')}`;
const lapItem = document.createElement('li');
lapItem.textContent = lapTime;
lapTimesList.append(lapItem);
}
}
startButton.addEventListener('click', function () {
startStopwatch();
});
stopButton.addEventListener('click', function () {
isRunning = false;
clearInterval(interval);
});
resetButton.addEventListener('click', function () {
isRunning = false;
clearInterval(interval);
hours = 0;
minutes = 0;
seconds = 0;
milliseconds = 0;
displayTime();
lapTimesList.innerHTML = '';
});
lapButton.addEventListener('click', lapRecord);
displayTime();