I am very new in React and I would like some help for my code. I have managed to code the setInterval (I know, it is not the best way of doing it) and clearInterval. Could you, please, check both function?
The code works somehow, but there are some bugs:
Bug1: When clicked many times the button “Start”, something strange hapens with stopwatch. It like the stopwatch starts many times at the same time (simultaneously).
Please, help. Thank you!
const [segundos, setSegundos] = React.useState(0)
const [minutos, setMinutos] = React.useState(0)
const [stopwatchid, setStopwatchid] = React.useState()
function stop () {
clearInterval(stopwatchid)
}
let counter_s = 0
let counter_m = 0
function count (){
const stopwatch = setInterval(function() {
if (counter_s == 60) {
counter_s = 0
counter_s++
if (counter_m == 0) {
counter_m = 0
}
}
counter_s++
setStopwatchid(stopwatch)
setSegundos(counter_s)
setMinutos(counter_m)
}, 1000)
}
return (
<main>
<button className="start" onClick={count}>Start</button>
<p>
<span>{minutos}</span>:<span>{segundos}</span>
</p>
<button className="stop" onClick={stop}>Stop</button>
</main>
)
user27393691 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
9