clearInterval在React Timer App中不起作用

时间:2017-05-24 00:15:24

标签: javascript reactjs clearinterval

我一直致力于通过创建番茄钟定时器应用程序来提高我的React技能。出于某种原因,我似乎无法让clearInterval工作:

startTimer() {
    const { started } = this.state;
    var timer;
    if (!started) {
      timer = setInterval(this.countdown, 1000);
      this.setState({ started: true });
    }
    else {
      clearInterval(timer);
      this.setState({ started: false });
    }
  }

没有控制台错误。可以确认它肯定正在运行条件语句的那一部分(当我记录this.state.started时它显示false)。计时器只是保持滴答声而实际上并没有停止。

其余代码:

import React, { Component } from 'react';

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      secs: 60,
      started: false
    };
    this.startTimer = this.startTimer.bind(this);
    this.countdown = this.countdown.bind(this);
  }

  countdown() {
    this.setState({ secs: this.state.secs - 1});
  }

  startTimer() {
    const { started } = this.state;
    var timer;
    if (!started) {
      timer = setInterval(this.countdown, 1000);
      this.setState({ started: true });
    }
    else {
      clearInterval(timer);
      this.setState({ started: false });
    }
  }

  render() {
    const { secs } = this.state;
    console.log('secs:', secs)
    console.log('started:', this.state.started);
    return (
      <div className='timer' onClick={this.startTimer}>
        <h2>Session</h2>
        <h1>{this.props.session}:{secs == 60 ? '00': secs}</h1>
      </div>
    );
  }
}

export default Timer;

2 个答案:

答案 0 :(得分:1)

在构造函数中初始化this.timer。然后创建setInterval并将其分配给this.timer,以便稍后将其清除。

import React, { Component } from 'react';

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      secs: 60,
      started: false
    };
    this.timer = null;
    this.startTimer = this.startTimer.bind(this);
    this.countdown = this.countdown.bind(this);
  }

  countdown() {
    this.setState({ secs: this.state.secs - 1});
  }

  startTimer() {
    const { started } = this.state;
    if (!started) {
      this.timer = setInterval(this.countdown, 1000);
      this.setState({ started: true });
    }
    else {
      clearInterval(this.timer);
      this.setState({ started: false });
    }
  }

  render() {
    const { secs } = this.state;
    console.log('secs:', secs)
    console.log('started:', this.state.started);
    return (
      <div className='timer' onClick={this.startTimer}>
        <h2>Session</h2>
        <h1>{this.props.session}:{secs == 60 ? '00': secs}</h1>
      </div>
    );
  }
}

export default Timer;

答案 1 :(得分:0)

如果您不想创建课程

 if(condition_is_true){
   const checkUntilConditionIsFalse = setInterval(() => {
    if (condition_is_false) {
      clearInterval(checkUntilConditionIsFalse);
    }
  }, 1000);
}