-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstopwatch.js
More file actions
45 lines (39 loc) · 1.47 KB
/
stopwatch.js
File metadata and controls
45 lines (39 loc) · 1.47 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
43
44
const time = document.querySelector('.stopwatch')
const mainButton = document.querySelector('#main-button')
const clearButton = document.querySelector('#clear-button')
const stopwatch = { elapsedTime: 0 }
mainButton.addEventListener('click', () => {
if (mainButton.innerHTML === 'Start') {
startStopwatch();
mainButton.innerHTML = 'Stop'
} else {
stopwatch.elapsedTime += Date.now() - stopwatch.startTime
clearInterval(stopwatch.intervalId)
mainButton.innerHTML = 'Start'
}
})
clearButton.addEventListener('click', () => {
stopwatch.elapsedTime = 0
stopwatch.startTime = Date.now()
displayTime(0, 0, 0, 0)
})
function startStopwatch() {
//reset start time
stopwatch.startTime = Date.now();
//run `setInterval()` and save id
stopwatch.intervalId = setInterval(() => {
//calculate elapsed time
const elapsedTime = Date.now() - stopwatch.startTime + stopwatch.elapsedTime
//calculate different time measurements based on elapsed time
const milliseconds = parseInt((elapsedTime%1000)/10)
const seconds = parseInt((elapsedTime/1000)%60)
const minutes = parseInt((elapsedTime/(1000*60))%60)
const hour = parseInt((elapsedTime/(1000*60*60))%24);
//display time
displayTime(hour, minutes, seconds, milliseconds)
}, 100);
}
function displayTime(hour, minutes, seconds, milliseconds) {
const leadZeroTime = [hour, minutes, seconds, milliseconds].map(time => time < 10 ? `0${time}` : time)
time.innerHTML = leadZeroTime.join(':')
}