Output of the given code
Use the following code:
HTML code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stopwatch Project</title>
// Use this if you use seprate css file
<link rel="stylesheet" href="./stopwatch.css">
</head>
<body>
<h1>STOPWATCH</h1>
<div class="stopwatch">
<div class="timeDisplay">
00 : 00 : 00
</div>
</div>
<div class="buttons">
<button class="btn" style="--color:red;" id="stop">Stop</button>
<button class="btn" style="--color:green;" id="start">Start</button>
<button class="btn" style="--color:blue;" id="reset">Reset</button>
</div>
// Use this if you use seprate JS file
<script src="./stopwatch.js"></script>
</body>
</html>
CSS code.
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
body{
background-color: #212121;
color: #ffffff;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
flex-direction: column;
}
h1{
font-size: 82px;
margin-bottom: 100px;
color:crimson;
}
.stopwatch{
background-color: #000;
padding: 30px 35px;
border-radius: 10px;
}
.timeDisplay{
font-size: 72px;
font-size: 700;
}
.buttons{
margin-top: 30px;
}
.btn{
font-size: 20px;
background: none;
border: none;
color: #ffffff;
background-color: var(--color);
padding: 12px 24px;
margin: 0px 12px;
cursor: pointer;
border-radius: 6px;
font-weight: 600;
}
JavaScript code.
let timeDisplay = document.querySelector('.timeDisplay');
let startBtn = document.getElementById('start');
let stopBtn = document.getElementById('stop');
let resetBtn = document.getElementById('reset');
let milliSeconds = 0;
let seconds = 0;
let minutes = 0;
let timer = null;
startBtn.addEventListener('click', ()=>{
if (timer != null) {
clearInterval(timer);
}
timer = setInterval(() => {
milliSeconds++;
if (milliSeconds == 100) {
milliSeconds = 0;
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
};
};
let ms = milliSeconds < 10 ? '0' + milliSeconds : milliSeconds;
let s = seconds < 10 ? '0' + seconds : seconds;
let m = minutes < 10 ? '0'+ minutes : minutes;
timeDisplay.innerHTML = `${m} : ${s} : ${ms}`;
}, 10);
});
stopBtn.addEventListener('click', ()=>{
clearInterval(timer);
});
resetBtn.addEventListener('click', ()=>{
clearInterval(timer);
milliSeconds = 0;
seconds = 0;
minutes = 0;
timeDisplay.innerHTML = '00 : 00 : 00';
});
Â