October 25, 2024
Chicago 12, Melborne City, USA
javascript

How can I stop a timer without using useState and useEffect?


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.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video