Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The timer does not stop with clearInterval

I’m trying to build a simple start and stop timer feature, however when i click again on the function, the clearInterval does not seem to do any effect. In fact the timer does not stop. However i’m able to start it but i cannot turn it off.

const [seconds, setSeconds] = useState(0);
const [timer, setTimer] = useState();

const handleStartToggle = (seconds) => {
  // Start new timer only if it's not run yet
  if(!timer) {
    setTimer(setInterval(() => {
      setSeconds((current) => current + 1);
    }, 1000));
  // Else, it's already running, we stop it
  } else {
    return () => clearInterval(timer);
  }
}

<div className="row project-task-showcase">
  <h2 className="client-name"> {activeClient.name}</h2>
  <p className="task-name">{activeTask.name}</p>
  <img src={play} className="play" onClick={handleStartToggle} />
  {seconds}
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Problem in return,
You returning as function, so in function it’s not working,

Change code to

const handleStartToggle = (seconds) => {
  // Start new timer only if it's not run yet
  if(!timer) {
    setTimer(setInterval(() => {
      setSeconds((current) => current + 1);
    }, 1000));
  // Else, it's already running, we stop it
  } else {
    clearInterval(timer);   // <-- Change here
   // setTimer(null); // <-- To toggle next time 
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading