FCC 25+5 Project

I’m having trouble with the countdown timer.

It stops when I click the play/pause button, stops at time zero, but for some reason counts down way too fast, increasingly fast as it continues to count down.

I set the interval to every 1000 milliseconds, so I’m not entirely sure what the problem is.

Here are the relevant parts of the code:

    countdown(){
        
      if(this.state.timerunning===true && this.state.timeleft > 0){
        this.setState(prevState => {
          return{
            timeleft: prevState.timeleft - 1
          }
        })
      
      
      }else{
        clearInterval(this.go);
      }
    
    }

The below toggles if the clock runs or not and is triggered by a button click:

    Running(){
       this.setState(prevState => {
        return{
            timerunning: !prevState.timerunning
        }})
     }

This is the componentWillUpdate where the interval is set with the countdown function, and componentWillUnmount to clear the interval

     componentWillUpdate(){
        this.go = setInterval(this.countdown.bind(this),1000);
      }
      
     componentWillUnmount(){
        clearInterval(this.go);
      }

Link to entire project: https://codepen.io/yisun1/pen/jOmMZmv?editors=1111

Hey yhsun21,

Can you move you remove the componentWillUpdate and componentWillUnmount call? I assume they cause you the headache.

Another advice: try to keep your code as simple as possible. Quite often, I program something and once I have a solution I “refactor”. Refactoring is a popular term in programming. It means that you improve your code, e.g. by making it simpler, without changing the functionality of it.

The same is true for your state. It is often desirable to keep as few state variables as necessary. Especially in React where excessive use of state leads to many Component re-renders and can cause performance issues.

best
Dennis

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.