0

I'm writing a countdown timer in React. I have two buttons: "pause-resume" and "reset" with onClick event handlers. clearInterval doesn't work in either of them

Struggling to understand what is wrong

  let timer = {
  minutes: 25,
  seconds: 0}
  
  let [remainingTime, setTime] = useState(timer);
  let [paused, setPaused] = useState(true);

let counting

function handleClick(e) {
  const targetId = e.currentTarget.id

  if (targetId === 'pause-resume') {
      setTime(remainingTime = {...remainingTime, seconds: remainingTime.seconds === 0 ? 59 : remainingTime.seconds})
    if (paused === true) {
      setPaused(false)
      counting = setInterval(() => {
        setTime(remainingTime = {...remainingTime, seconds: remainingTime.seconds - 1})}, 1000)
    } else {
      clearInterval(counting)
      setPaused(true)
      
    }
  } else if (targetId === 'reset') {
    clearInterval(counting);
    setTime(timer)
  }
}
ddc1
  • 1
  • 2
  • where do you declare `counting`? Unless you store it in a `ref` or state it will be redeclared on each render. – pilchard Aug 03 '22 at 23:59
  • Make `counting` a `ref` – Phil Aug 04 '22 at 00:00
  • `setInterval` requires some specific juggling in React with hooks, use the implementation from https://overreacted.io/making-setinterval-declarative-with-react-hooks (which is also a very good explanation) – Andy Ray Aug 04 '22 at 00:02
  • I've seen this exact implementation of setInterval without ref, but mine for some reason doesn't work. @AndyRay Ok, thank you I will look into that – ddc1 Aug 04 '22 at 08:52
  • @pilchard yeah, that was my problem, my `counting` was inside App component, thank you – ddc1 Aug 04 '22 at 13:31

0 Answers0