Home > Blockchain >  Pause in React timer count
Pause in React timer count

Time:08-02

I am trying to achieve the pause in react count down timer. Here is code:

export default function Home() {
  const timerRef = useRef(180)

  const [minute, setMinute] = useState(3)
  const [second, setSecond] = useState(59)
  const [isPaused, setIspaused] = useState(false)
 
  let timeInterval
  let startTimer = () => {
    timerRef.current = timerRef.current - 1
    //setSecond((prev) => parseInt(timerRef.current % 60))   <-------important
    console.log(` second in this ${parseInt(timerRef.current % 60)}`)
    console.log(` minute in this ${parseInt(timerRef.current / 60)}`)
  }
  let startInterval = () => {
    clearInterval(timeInterval)
    timeInterval = setInterval(() => {
      startTimer()
    }, 1000)
  }

  let paused = () => {
    console.log("Paused clicked")
    clearTimeout(timeInterval)
   
  }

  return (
    <>
      <div className="">
        <div className="tw-flex tw-border-2">
          <div className="tw-my-1 tw-p-2">{minute}</div>
          <div className="tw-my-1 tw-p-2">{second}</div>
        </div>
        <br />

        <div className="tw-flex">
          <button
            className="tw-bg-green-400 tw-p-1 tw-mx-2"
            onClick={startInterval}
          >
            start
          </button>
          <button className="tw-bg-green-400 tw-p-1 tw-mx-2" onClick={paused}>
            paused
          </button>
        </div>
      </div>
    </>
  )
}

This is working fine but when I use the setSecond in startTimer , rather than pause it continues to run the timer. But when there is no setState(setsecond) it's working fine

  1. Why it is behaving in such a way with setState ?
  2. How can we fix it

CodePudding user response:

When you change ref component dont rerender but when you change state like setSecond or setMinute your component rerender and timer reset. You can use ref for your minute or second

  • Related