I am making a stop watch and the setInterval seems to be restarting on it's own after I tell it to stop or it doesn't stop at all.
What I want is that when I press Stop the setInterval stops cycling but keeping the number it's at unless the reset button is clicked.
const sw = {
time: 0,
reset: ()=>{
clearInterval(sw.stopWatch)
sw.time = 0
},
stop: ()=>{
clearInterval(sw.stopWatch)
console.log("stop")
},
stopWatch: ()=>{
setInterval(function(){
sw.time ++
document.getElementById("time").innerHTML = sw.time
}, 1000)
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="index.js"></script>
</head>
<body>
<div id="time">0</div>
<button onclick="sw.stopWatch()">Start</button>
<button onclick="sw.stop()">Stop</button>
<button onclick="sw.reset()">Reset</button>
</body>
</html>