ClearInterval 不清除相同的 SetInterval

时间:2021-01-06 06:13:52

标签: javascript reactjs

我开始使用 react 创建一个计时器。我在状态中使用“timerState”来检查间隔的状态。然后我创建函数“startStop”以根据“timerState”切换开始和停止间隔。每次单击“startStop”按钮时,它都会添加一个新的间隔但不会清除最后一个。问题出在哪儿?代码如下:

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

}

1 个答案:

答案 0 :(得分:0)

您似乎在行 if (this.state.timerState = "paused") 上打错了。

您应该改用 ===,实际情况是此条件总是被评估为真,并且代码永远不会达到您使用 clearInterval 的 else-if 条件

相关问题