Recently I was working on a stopwatch project in JavaScript. Few things I encountered. First when I assign a variable to the setInterval() function like let sInterval = setInterval(functionName, milliseconds)
. I was unable to pass it to an eventListener. But when I do this: sInterval = () => setInterval(functionName, milliseconds)
, I can pass it to the eventListener and start the stopwatch. But when I now want to stop the stopwatch, it doesn't work. I have no idea what's going wrong and don't know how to fix it. Please help :/
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="stopwatch">
<meta name="description" content="stopwatch">
<meta name="author" content="Nick">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stopwatch.css">
<script src="stopwatch.js"></script>
</head>
<body>
<h1>STOPAWATCH</h1>
<h1>JAVASCRIPT STOPWATCH</h1>
<div id="stopwatch"></div>
<button id="button-start">Start</button>
<button id="button-stop">Stop</button>
<button id="button-reset">Reset</button>
</body>
</html>
* {
box-sizing: border-box;
}
body {
margin: 0;
text-align: center;
background-color: orange;
font-family:'Courier New', Courier, monospace;
font-size: 100%;
color: white;
}
h1 {
font-size: 3em;
font-weight: normal;
}
#stopwatch {
font-size: 3em;
margin-bottom: 20px;
}
[id|="button"] {
background-color: orange;
color: white;
width: 20%;
height: 80px;
font-size: 1.5em;
margin: 3%;
border: 1px solid white;
border-radius: 5px;
}
[id|="button"]:hover {
cursor: pointer;
color: orange;
background-color: white;
}
window.onload = () => {
let start = document.getElementById("button-start");
let stop = document.getElementById("button-stop");
let reset = document.getElementById("button-reset");
let stopwatch = document.getElementById("stopwatch");
let h, m, s;
initialize = () => {
h = m = s = "0" + 0;
stopwatch.innerHTML = `${h}:${m}:${s}`;
}
let sInterval = () => setInterval(() => {
s++;
if (s < 10 && s[0] !== "0") {
s = "0" + s;
} else if (s === 60) {
m++;
s = "0" + 0;
}
if (m < 10 && m[0] !== "0") {
m = "0" + m;
} else if (m === 60) {
h++;
m = "0" + 0;
}
if (h < 10 && h[1] !== "0") {
h = "0" + h;
}
stopwatch.innerHTML = h + ":" + m + ":" + s;
}, 1000);
reset.addEventListener("click", () => {
clearInterval(sInterval);
initialize();
});
start.addEventListener("click", sInterval);
stop.addEventListener("click", clearInterval(sInterval));
initialize();
}