繁体   English   中英

ClearInterval 不会清除相同的 SetInterval

[英]ClearInterval does not clear the same SetInterval

我开始使用 react 来创建一个计时器。 我在 state 中使用“timerState”来检查间隔的状态。 然后我创建 function "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)})
    }

}

if (this.state.timerState = "paused") ,您似乎有错字。

您应该使用===代替,发生的情况是此条件始终被评估为 true,并且代码永远不会达到您使用clearInterval的 else-if 条件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM