Why my decreasing-time-function isn't working?

Viewed 47

I'm trying to make a pomodori timer in React but the function that should decrease timer when it's on isn't pausing.

This is my function:

const runTime = () =>{
    let date = new Date().getTime();
    let nextDate = new Date().getTime() +1000;
    if(active){
      let interval = setInterval(()=>{
        date = new Date().getTime();
        if(date>nextDate && active){
          setTime((prev)=>{
            return prev-1;
          });
          nextDate+=1000;
        }
      },30)
      }
    localStorage.clear();
    localStorage.setItem('interval-id', interval);
    if(!active){
      clearInterval(localStorage.getItem('interval-id'));
    }
  }

and the variables used is this:

const [sessionTime, setSessionTime] = React.useState(25*60);
const [active, setActive] = React.useState('false');
const [time, setTime] = React.useState(sessionTime);

1 Answers

I think your issue may come from how you're passing the boolean value to useState. You're passing a string useState('false'), instead of passing it as boolean useState(false). I'm guessing that active is always truthy because it's a string of characters, so falsy !active never occurs.

So change useState('false') to useState(false)

At least that's my guess. Hope it fixes it for you.

Related