“In a simple timer component, I want to start and stop it with buttons, but the interval does not stop with a simple clearInterval function. Is there something I am missing?”
import React, { useState } from 'react'
export default function Timer3() {
const [seconds, setseconds] = useState(0)
let intervalId;
const startTimer = () => {
intervalId = setInterval(() => {
setseconds((pre) => pre + 1)
}, 1000)
}
const stopTimer = () => {
clearInterval(intervalId)
}
return (
<>
{seconds}
<button onClick={startTimer}>start</button>
<button onClick={stopTimer}>stop</button>
</>
)
}
I know that in the code above, there is a bug: if I press “Start” twice, it will count twice. I am going to fix this after finding out how to make it stop. There is also a solution on the web to use useEffect to run the timer, but I am not looking for codeājust a simple answer as to why it does not work.