Home > Blockchain >  The timer does not stop with clearInterval
The timer does not stop with clearInterval

Time:06-03

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>

CodePudding user response:

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 
  }
}

CodePudding user response:

In your handleStartToggle function you are doing different work for if and else statement. For if you are executing few statement but for else you are returning a arrow function that is not correct. To correct this you have to either return function in both

const handleStartToggle = (seconds) => {
// Start new timer only if it's not run yet
if(!timer) {
   return () => {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>

Or use statement in both

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 
}

}

  • Related