Pomodoro Clock - setInterval() not working correctly

Hello,

I am working on Pomodoro Clock project and having trouble with setInterval() in React function.

The below decrementDisplayTimer() decrements the time on the main display every second and it works if I set this function on “Start/Stop” button and press it manually.

decrementDisplayTimer(){
    console.log(this.state.timeLeft)
    var minutes = Math.floor(this.state.timeLeft / 60); 
    var seconds = this.state.timeLeft % 60; 
    this.state.timeLeft--;
      minutes = Math.floor(this.state.timeLeft / 60);
      seconds = this.state.timeLeft % 60; 
      this.setState({
        timeLeft:this.state.timeLeft,
        timerDisplay: minutes + ":" + seconds,
      });
  }

However, when I set this function in countDownHandlar() as below, the count down doesn’t start from the main display count (timeLeft:1500). I checked the console.log (this.state.timeLeft) to see what’s going on and it seems like it always start counting down from “3” and I can’t figure out where the number is coming from.

  countDownHandlar(){
    let startCountdown = setInterval(()=>{
        this.decrementDisplayTimer();
        if(this.state.timeLeft===0){
          console.log("done!")
          clearInterval(startCountdown)
        }
      }, 1000)
    this.setState({
      timeLeft: startCountdown
    })
  }

It would be great if someone could help me on this.

Here is my codepen: https://codepen.io/eriko87/pen/PrdeqN

Thanks!

You have several issues currently, but I will tell you why the countdown starts at numbers like 3 or 4. setInterval returns a value representing an id which you can later use to clear the interval. So when you have the following setState:

    this.setState({
      timeLeft: startCountdown
    })

you are just assigning the value of the interval’s id. If you delete the lines of code above, this will at least get your timer started with the correct time. Once you fix this issue, you will find new issues you will need to resolve.

Thank you! it works now! I will work on the new issues…