Ramosok,
лучше код не кусками, а всё сразу ...
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>stopwatch</title>
<style>
* {
box-sizing: border-box;
}
#stopwatch {
background-color: #ededed;
border: 1px solid #000;
border-radius: 3px;
width: 150px;
}
#stopwatch p {
background-color: #fff;
border: 1px solid #000;
border-radius: 3px;
padding: 3px;
width: 80%;
margin-left: 10%;
text-align: center;
}
#stopwatch button {
width: 5em;
}
h6 {
font-size: 20px;
}
</style>
</head>
<body>
<div id="stopwatch">
<p>00:00:000</p>
<button class="startstopref">Старт</button>
<button class="lap">Круг</button>
</div>
<script>
const startstopref = document.querySelector('.startstopref');
let lap = document.querySelector('.lap');
let p = document.querySelector('p');
let startTime;
let RAF;
let laps;
function reset() {
document.querySelectorAll('h6').forEach(element => element.remove())
}
function add(x, y) {
return x.toString().padStart(y, '0')
}
function formatAndShow(ms, element) {
ms = Math.trunc(ms);
let s = Math.floor(ms / 1000);
ms = ms % 1000;
let m = Math.floor(s / 60);
s = s % 60;
element.innerHTML = [add(m, 2), add(s, 2), add(ms, 3)].join(':');
}
function clockRun(nowTime) {
let ms = nowTime - startTime;
formatAndShow(ms, p)
RAF = requestAnimationFrame(clockRun);
}
startstopref.addEventListener('click', funcButtons);
function funcButtons() {
switch (this.innerHTML) {
case 'Старт':
startTime = laps = performance.now();
this.innerHTML = 'Стоп';
clockRun();
break;
case 'Стоп':
this.innerHTML = 'Сброс';
cancelAnimationFrame(RAF);
break;
case 'Сброс':
this.innerHTML = 'Старт';
p.innerHTML = '00:00:000';
reset();
break;
}
}
lap.addEventListener('click', () => {
let h6 = document.createElement('h6');
document.body.append(h6);
let ms = performance.now() - laps;
laps = performance.now();
formatAndShow(ms, h6)
})
</script>
</body>
</html>