带有启动/暂停和重置按钮的倒数计时器

时间:2019-02-17 12:38:43

标签: javascript reactjs

我想在React JS中使用“开始”,“暂停”和“重置”按钮创建一个countDown计时器,以便操作该计时器。作为React和JS的初学者,我创建了一个状态变量“ secondsElapsed”,以输入计时器的秒数。

“ startTime”功能用于每秒钟启动计时器的倒计时。 “ resetTime”功能用于将“ secondsElapsed”重置为0。 “ pauseTime”功能用于暂停计时器。

其他功能是计算时间并在特定字段中返回时间。

在此处描述图片

Discriptive Timer

点击“开始按钮”后倒数计时正常,秒数减少。问题在于分钟和小时字段没有像应该每分钟和每小时那样减少。

这是我的密码和框链接:https://codesandbox.io/s/y3l1ymq6r1

这是我的React Js代码:

import React from "react";

export default class Timer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      secondsElapsed: 122 //time in seconds
    };
  }

  getHours() {
    return ("0" + Math.round(this.state.secondsElapsed / 3600)).slice(-2);
  }

  getMinutes() {
    return ("0" + Math.round((this.state.secondsElapsed % 3600) / 60)).slice(
      -2
    );
  }

  getSeconds() {
    return ("0" + (this.state.secondsElapsed % 60)).slice(-2);
  }

  startTime() {
    var _this = this;
    this.countdown = setInterval(function() {
      _this.setState({ secondsElapsed: _this.state.secondsElapsed - 1 });
    }, 1000);
  }

  resetTime() {
    this.reset = this.setState({
      secondsElapsed: (this.state.secondsElapsed = 0)
    });
  }

  pauseTime() {
    clearInterval(this.countdown);
  }

  render() {
    return (
      <div className="App">
        <h1>
          {this.getHours()}:{this.getMinutes()}:{this.getSeconds()}
        </h1>
        <button onClick={() => this.startTime()}>Start</button>
        <button onClick={() => this.pauseTime()}>Pause</button>
        <button onClick={() => this.resetTime()}>Reset</button>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,我将与Math.floor()合作,而您必须向上而不是向下计数。

计时器:

_this.setState({ secondsElapsed: _this.state.secondsElapsed + 1 });

分钟:

return ("0" + Math.floor((this.state.secondsElapsed % 3600) / 60)).slice(-2);

小时:

return ("0" + Math.floor(this.state.secondsElapsed / 3600)).slice(-2);
相关问题