在React中停止与另一个函数的间隔

时间:2018-03-01 11:50:29

标签: javascript reactjs

我是React的新手,我尝试构建一个计时器组件。现在我有启动功能,但我也希望通过onclick处理程序停止计时器。问题是start函数使用了一个区间,但我不知道如何从另一个函数中停止该区间。

我的JS代码

  constructor() {
    super();

    this.state = {
      times: [],
      timer: false,
      currentTimer: 0
    }

    this.startTimer = this.startTimer.bind(this);
    this.stopTimer = this.stopTimer.bind(this);

  }

  startTimer() {

    const start = Date.now();

    this.setState({ timer: true });

    var timer = setInterval(() => {

      let time = new Date() - start;

      this.setState({ currentTimer: Math.round(time / 1000)});


    }, 1000);

  }

  stopTimer() {

    this.setState({ timer: false });
    console.log('stopped');

    //Clear interval here

  }

我知道timer变量是该间隔的标识符,但我如何访问它然后停止它?我几乎尝试了一切,但似乎没有任何工作,我只是不知道如何解决这个问题。

3 个答案:

答案 0 :(得分:3)

要停止计时器,您需要计时器ID,因此,第一个作业将以这样的方式存储id,使其在所有类方法中都可以访问。 第二个作业将使用clearInterval来清除计时器(此处将需要计时器ID)。

一个选项是,将计时器ID存储在类实例中。

像这样:

startTimer() {
    const start = Date.now();
    this.setState({ timer: true });
    // storing the id
    this.timerID = setInterval(() => {
        let time = new Date() - start;
        this.setState({ currentTimer: Math.round(time / 1000)});
    }, 1000);
}

stopTimer() {
    this.setState({ timer: false });
    clearInterval(this.timerID);
}

工作代码:

class App extends React.Component {

  constructor(){
     super();
     this.state = {currentTimer: ''}
     this.startTimer = this.startTimer.bind(this);
     this.stopTimer = this.stopTimer.bind(this);
  }
  
  startTimer() {
    const start = Date.now();
    this.timerID = setInterval(() => {
        let time = Math.random() * 10;
        this.setState({ currentTimer: time});
    }, 1000);
  }

  stopTimer() {
     clearInterval(this.timerID);
  }
  
  render(){
     return (
        <div>
          Value: {this.state.currentTimer || '0'}
          <br />
          <button onClick={this.startTimer}>Start timer</button>
          <button onClick={this.stopTimer}>Stop timer</button>
        </div>
     )
  }

}

ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app' />

答案 1 :(得分:2)

将timerId保存为类实例变量,然后可以从其他函数访问并用于清除间隔

constructor() {
    super();

    this.state = {
      times: [],
      timer: false,
      currentTimer: 0
    }
    this.timer = null;

    this.startTimer = this.startTimer.bind(this);
    this.stopTimer = this.stopTimer.bind(this);

  }

  startTimer() {

    const start = Date.now();

    this.setState({ timer: true });

    this.timer = setInterval(() => {

      let time = new Date() - start;

      this.setState({ currentTimer: Math.round(time / 1000)});


    }, 1000);

  }

  stopTimer() {

    this.setState({ timer: false });
    console.log('stopped');

    //Clear interval here
    clearInterval(this.timer)
  }

答案 2 :(得分:1)

您的timer变量是startTimer()方法的局部变量,它存储该间隔的标识符,但在函数范围之外无法访问。

要解决此问题,请在constructor()方法中添加以下内容:

this.timer = null;

然后,在startTimer()方法更改:

var timer = setInterval(() => {

  let time = new Date() - start;

  this.setState({ currentTimer: Math.round(time / 1000)});


}, 1000);

为:

this.timer = setInterval(() => {

  let time = new Date() - start;

  this.setState({ currentTimer: Math.round(time / 1000)});


}, 1000);

最后,在stopTimer()方法中添加以下内容:

//Clear interval here code here
clearInterval(this.timer);