在倒计时器中放置setTimeout的位置

时间:2017-11-19 05:32:22

标签: javascript reactjs

在React中使用倒数计时器而不了解如何/在何处放置setTimeout函数。它似乎在返回之前将它放在渲染中时起作用,但是状态属性没有被定义,所以它从零开始计数到负数:/我尝试过这样的事情:

 class App extends React.Component {
 constructor(props) {
    super(props)
    this.state = {
      start: '', //'10:10:10'
      end: '',
      startSec: '', //'36610'
      endSec: ''
    }
    this.clicked = this.clicked.bind(this);
    this.handleTimeout = this.handleTimeout.bind(this);
  }

  handleTimeout() {
    // decrement state.startSec
    //^thought this would trigger re-render every sec when  
    //called in clicked() 

  }

  clicked() {
    let re=/^([0-1]\d|2[0-3]):([0-5]\d):([0-5]\d)$/;
    let validStart = re.test(this.state.start);
    let validEnd = re.test(this.state.end);
    let start = this.state.start.split(":");
    let end = this.state.end.split(":");
    let startSec =  (Number(start[0]) * 3600) + (Number(start[1]) * 60) + (Number(start[2]));
    let endSec = (Number(end[0]) * 3600) + (Number(end[1]) * 60) + (Number(end[2]));


    // validate inputs
    if(!validStart || !validEnd) { alert('please use format HH:MM:SS') }     
    if(endSec > startSec) {
      alert('Please make end time less than start time!');
    }

    //where I am stuck
    this.setState({ startSec: startSec }); 

    if(this.state.startSec > this.state.endSec) {
      setInterval(this.handleTimeout() ,1000);
    }
  }

  render () {
    return (
      <div>
        <h2> Timer </h2>
        <div id="timer">
          Start Time <input type="text" placeholder="hh:mm:ss" onChange={(e) => {this.setState({start: e.target.value})}} /><br />
          End Time <input type="text" placeholder="hh:mm:ss" onChange={(e) => {this.setState({end: e.target.value})}}/> <br /><br />
          <button onClick={this.clicked}> Start Countdown </button><br /><br />
          <div id="output">{this.state.startSec}</div>
        </div>
      </div>
    );
  }
}

已更新 https://jsfiddle.net/lydiademi/69z2wepo/91973/

我引用了与Countdown timer in React

等计时器相关的帖子

但无法解决此问题,

感谢您的帮助..!

1 个答案:

答案 0 :(得分:0)

它只调用一次的原因是你需要将函数传递给setInterval,而是调用函数并传递它的返回值(未定义)。

所以而不是

setInterval(this.handleTimeout() ,1000);

应该是

setInterval(this.handleTimeout ,1000);
  • 您需要跟踪之前启动的间隔,以便在开始新的间隔之前停止它们

if(this.currentInterval) {
  clearInterval(this.currentInterval);
}
this.currentInterval = setInterval(this.handleTimeout, 1000);