在React中创建一个计时器

时间:2018-07-22 20:46:07

标签: javascript reactjs

如果这看起来太简单了,请原谅我...这是我在React中做过的第一件事,所以我只是想把事情包裹住。我已经意识到我应该拥有较小的组件,例如按钮,并用道具和所有这些东西渲染它们(目标是稍后进行重构!),但是目前我很难弄清楚如何使用setInterval方法更改状态,并且然后停止。

我正在构建一个番茄计时器,一般的想法是我的状态是保持计时器应该离开的总秒数。我还有另一个功能,可以将总秒数转换成我要显示的时间格式。

我的挣扎在我的startStop()方法中,我想将运行状态(计时器正在运行)更改为t / f,这将起作用,但是显然我正在用setInterval做些事情。我想设置一个间隔(有剩余时间时)以每秒将状态更改为少1秒。当我再次单击该按钮时,间隔计时器将停止,当前剩余的“状态”秒将保持不变,因此,如果再次单击该按钮,它将再次启动计时器。

感谢您的帮助! (所有这些都是从create-react-app渲染的,因此需要在我的github上进行更多操作:https://github.com/ryanmdoyle/web-pomodoro

    import React, { Component } from "react ";

    class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sessionTimeEntry: 25, //in min
      breakTimeEntry: 5, //in min
      sessionRemainingSeconds: 1500, //in seconds
      breakRemainingSeconds: 300, //in seconds
      running: false,
      timerLabel: "Session"
    }
    this.addSession = this.addSession.bind(this);
    this.subSession = this.subSession.bind(this);
    this.addBreak = this.addBreak.bind(this);
    this.subBreak = this.subBreak.bind(this);
    this.startStop = this.startStop.bind(this);
    this.resetTimer = this.resetTimer.bind(this);
    this.formatMinutes = this.formatMinutes.bind(this);
  }

  addSession() { //adding and subtracting methods need to also chage the session remaining in seconds to mirrow the entry time if ever changed
    this.setState({
      sessionTimeEntry: this.state.sessionTimeEntry + 1,
      sessionRemainingSeconds: this.state.sessionRemainingSeconds + 60
    })
  }

  subSession() {
    this.setState({
      sessionTimeEntry: this.state.sessionTimeEntry - 1,
      sessionRemainingSeconds: this.state.sessionRemainingSeconds - 60

    })
  }

  addBreak() {
    this.setState({
      breakTimeEntry: this.state.breakTimeEntry + 1,
      breakRemainingSeconds: this.state.breakRemainingSeconds + 60
    })
  }

  subBreak() {
    this.setState({
      breakTimeEntry: this.state.breakTimeEntry - 1,
      breakRemainingSeconds: this.state.breakRemainingSeconds - 60
    })
  }

  startStop() {

    let timer;
    const status = this.state.running;

    switch (status) {
      case false:
        console.log("should start!")
        this.setState({
          running: true
        })

        while (this.state.breakRemainingSeconds > 0) {
          timer = setInterval(() => {
            this.setState({
              breakRemainingSeconds: this.state.breakRemainingSeconds - 1
            });
            console.log(this.state.breakRemainingSeconds);
          }, 1000)
        }

        break;
      case true:
        console.log("should stop")
        this.setState({
          running: false
        })
        clearInterval(timer)
        break;
      default:
        break;
    }

  }

  resetTimer() {
    this.setState({
      sessionTimeEntry: 25,
      breakTimeEntry: 5,
      sessionRemainingSeconds: 1500,
      breakRemainingSeconds: 300,
      running: false,
      timerLabel: "Session"
    })
  }

  formatMinutes(time) {
    let seconds = time;
    const minutes = (seconds % 60 === 0) ? ((seconds / 60) < 10 ? "0" + seconds / 60 : seconds / 60) : (Math.floor(seconds / 60) < 10 ? "0" + Math.floor(seconds / 60) : Math.floor(seconds / 60));
    seconds = (seconds % 60 === 0) ? "00" : ((seconds % 60 < 10) ? "0" + (seconds % 60) : seconds % 60)
    console.log(minutes + ":" + seconds);
    return minutes + ":" + seconds;
  }

  render() {
    return ( <
      div >
      <
      h1 > Pomodoro Clock < /h1> <
      h2 > {
        this.state.sessionTimeEntry
      } < /h2> <
      div id = 'timerContainer' >
      <
      h3 id = "session-label" > Session Time < /h3> <
      h3 id = "session-length" > {
        this.formatMinutes(this.state.sessionRemainingSeconds)
      } < /h3> <
      button onClick = {
        this.addSession
      }
      id = "session-increment" > ^ < /button> <
      button onClick = {
        this.subSession
      }
      id = "session-decrement" > v < /button> <
      /div> <
      div id = 'timerContainer' >
      <
      h3 id = "break-label" > Break Time < /h3> <
      h3 id = "break-length" > {
        this.state.breakTimeEntry
      } < /h3> <
      button onClick = {
        this.addBreak
      }
      id = "break-increment" > ^ < /button> <
      button onClick = {
        this.subBreak
      }
      id = "break-decrement" > v < /button> <
      /div> <
      div >
      <
      button onClick = {
        this.startStop
      }
      id = "start-stop" > Start / Stop < /button> <
      button onClick = {
        this.resetTimer
      }
      id = "reset" > Reset < /button> <
      /div> <
      /div>
    )
  }

}

export default App;

****************更新*****************

想通了!这是工作中的代码笔的链接,以查看其实际运行情况。

https://codepen.io/ryanmdoyle/pen/vaxoaG

3 个答案:

答案 0 :(得分:2)

我认为问题出在您的startStop函数中。请从您的函数中删除while循环。

startStop() {
    const status = this.state.running;

    switch (status) {
        case false:
          console.log("should start!")
          this.setState({
              running: true
          })

          this.timer = setInterval(() => {
              this.setState({
                  breakRemainingSeconds: this.state.breakRemainingSeconds - 1
              });
              console.log(this.state.breakRemainingSeconds);
          }, 1000)
        }

        break;
        case true:
          console.log("should stop")
          this.setState({
            running: false
          }) 
          clearInterval(this.timer)
          break;
        default:
          break;
    }

}

答案 1 :(得分:1)

您可以创建一个let password:String = "SuperSecret123" ,该setInterval每秒减少breakRemainingSeconds,并将setInterval返回的ID存储在实例上。要稍后停止计时器,可以稍后使用clearInterval(this.timer)

startStop() {
  const { running } = this.state;

  if (running) {
    this.setState({
      running: false
    });
    clearInterval(this.timer);
  } else {
    this.setState({
      running: true
    });

    this.timer = setInterval(() => {
      this.setState(previousState => {
        return {
          breakRemainingSeconds: previousState.breakRemainingSeconds - 1
        };
      });
    }, 1000);
  }
}

答案 2 :(得分:1)

我建议使用moment之类的库。只需将其安装为依赖项即可: npm i react-moment ,因为JS在日期和时间上可能有些棘手。无论如何,这是一个可以帮助您入门的功能。希望对您有所帮助。我用您的breakRemainingSeconds进行了演示,但是您可以对其进行调整,以实现组件中可能还需要的所有“时间”管理。

    class Timer extends React.Component {
    constructor() {
    super();
    this.state = { 
    time: {}, 
    breakRemainingSeconds: 300
    };
    
    this.timer = 0;
    this.startTimer = this.startTimer.bind(this);
    this.countDown = this.countDown.bind(this);
  }

// Let's make some sense of JS date and time It can get a little bit tricky sometimes.
// So, what we're doing here is taking the values and converting it in hours minutes, seconds. 
// In the example below we are using minutes and seconds, but just in case we got hours in there too :)

    createTime(secs){
      let hours = Math.floor(secs / (60 * 60));
      let divisor_for_minutes = secs % (60 * 60);
      let minutes = Math.floor(divisor_for_minutes / 60);
      let divisor_for_seconds = divisor_for_minutes % 60;
      let seconds = Math.ceil(divisor_for_seconds);

    let timeObject = {
      "h": hours,
      "m": minutes,
      "s": seconds
    };
    return timeObject;
  }

  componentDidMount() {
 // Taking the starting point  -> breakRemainingSeconds <-
// Passing it as the parameter and setting the state's time object to it.
    let timeLeft = this.createTime(this.state.breakRemainingSeconds);
    this.setState({ time: timeLeft });
  }

// Check the current state and potentially (if != 0) start our main function 
  startTimer() {
    if (this.timer == 0) {
      this.timer = setInterval(this.countDown, 1000);
    }
  }

countDown() {
    // Remove one second, set state so a re-render happens.
    let seconds = this.state.breakRemainingSeconds - 1;
    this.setState({
      time: this.createTime(seconds),
      breakRemainingSeconds: seconds
    });
    
    // Check if we're at zero, and if so, clear the Interval
    if (seconds == 0) { 
      clearInterval(this.timer);
    }
  }

  render() {
    return(
      <div>
        <button 
                onClick={this.startTimer} style={{marginRight:'12px'}}>Let's Go</button>
        m: {this.state.time.m} s: {this.state.time.s}
      </div>
    );
  }
}

ReactDOM.render(<Timer/>, document.getElementById('container'));
    <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="container"></div>

我在这里放置了一个 button 来开始该过程,但是如果要在组件渲染后立即开始, this.startTimer(); 内的 {strong> 生命周期 >