Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - ClearInterval does not clear the same SetInterval

I start using react to create a timer. I use "timerState" in the state for checking the status of the interval. Then I create function "startStop" to toggle start and stop the interval base on the "timerState". Every time I click "startStop" button, it adds a new interval but not clear the last one. Where is the problem? Here's the code:

class App extends Component {
  state = {
    breakLength: 5,
    sessionLength: 25,
    timerState: "paused",
  }

 startStop() {
    
    var mins = this.state.sessionLength
    var secs = mins * 60

    var minutes = document.getElementById("minutes")
    var seconds = document.getElementById("seconds")

    function getminutes() { 
      //minutes is seconds divided by 60, rounded down 
      return mins = Math.floor(secs / 60)
    } 

    function getseconds() { 
      //take minutes remaining (as seconds) away  
      //from total seconds remaining 
      return secs - Math.round(mins * 60)
    } 

    function decrement() {

      function appendZero(number) {
        if (number <= 9)
          return "0" + number
        else
          return number
      }

        minutes.innerHTML = appendZero(getminutes())
        seconds.innerHTML = appendZero(getseconds())
        secs = secs - 1

    }

    if (this.state.timerState = "paused") {
      this.setState({
        timerState: setInterval(() => decrement(), 1000)
      }, function () {console.log(this.state.timerState)})
    }
    
    else if (this.state.timerState !== "paused") {
      clearInterval(this.state.timerState)
      this.setState({
        timerState: "paused"
      }, function () {console.log(this.state.timerState)})
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems like you have a typo on the line if (this.state.timerState = "paused").

You should use === instead, what's happening is that this condition is always being evaluated as true and the code is never reaching the else-if condition where you use clearInterval


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...