简体   繁体   English

如何通过单击停止 setInterval 中的计时器,然后再次单击恢复?

[英]how to stop a timer in setInterval by click then resume by click again?

I am new to react, I am trying to write a react component, component has several features.我是 React 新手,我正在尝试编写一个 React 组件,该组件有几个特性。

  1. user can input a random number, then number will be displayed in the page too.用户可以输入一个随机数,然后这个数字也会显示在页面中。
  2. implement a button with text value 'start', once click the button, the number value displayed will reduce one every 1second and the text value will become 'stop'.实现一个文本值为'start'的按钮,一旦点击该按钮,显示的数值将每1秒减少一个,文本值变为'stop'。
  3. continue click button, minus one will stop and text value of button will become back to 'start'.继续单击按钮,减一将停止,按钮的文本值将变回“开始”。
  4. when number subtract to 0 will automatically stop itself.当数字减到 0 时会自动停止。

I have implemented the first and second feature.我已经实现了第一个和第二个功能。 but when I try to click stop to stop number from reducing 1, it does not work.但是当我尝试单击停止以阻止数字减少 1 时,它不起作用。

I am wondering since I used type=true/false to indicate the state of type is start or stop.我想知道因为我使用type=true/false来指示类型的状态是开始还是停止。 Because in the start state, number should automatically reduce 1. And on the stop state, reducing 1 should stop.因为在开始状态,数字应该自动减1。而在停止状态,减1应该停止。 So, the timer function should accurate according to the state of type.因此,定时器功能应根据类型的状态准确。

Also I am not sure if I used clearInterval method right.另外我不确定我是否正确使用了clearInterval方法。

I really appreciate if someone could give me a hand.如果有人能帮我一把,我真的很感激。

code is here:代码在这里:

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          details: [{ id: 1, number: "" }],
          type: false
        };
        this.handleClick = this.handleClick.bind(this);
      }
      changeNumber = (e, target) => {
        this.setState({
          details: this.state.details.map(detail => {
            if (detail.id === target.id) {
              detail.number = e.target.value;
            }
            return detail;
          })
        });
      };

      handleClick = () => {
        this.setState(prevState => ({
          type: !prevState.type
        }));
        if (this.state.type === false) {
          var myTimer = setInterval(
            () =>
              this.setState({
                details: this.state.details.map(detail => {
                  if (detail.id) {
                    detail.number = parseInt(detail.number) - 1;
                  }
                  return detail;
                })
              }),
            1000
          );
        } else if (this.state.type === true) {
          clearInterval(myTimer);
        }
      };

      render() {
        return (
          <div>
            {this.state.details.map(detail => {
              return (
                <div key={detail.id}>
                  Number:{detail.number}
                  <input
                    type="number"
                    onChange={e => this.changeNumber(e, detail)}
                    value={detail.number}
                  />
                  <input
                    type="button"
                    onClick={() => this.handleClick()}
                    value={this.state.type ? "stop" : "start"}
                  />
                </div>
              );
            })}
          </div>
        );
      }
    }

    export default App;

You need to declare var myTimer outside of the handleClick() function.您需要在handleClick()函数之外声明var myTimer

So it's something like:所以它是这样的:

var myTimer;

...

handleClick = () => {
        this.setState(prevState => ({
          type: !prevState.type
        }));
        if (this.state.type === false) {
          myTimer = setInterval(
            () =>
              this.setState({
                details: this.state.details.map(detail => {
                  if (detail.id) {
                    detail.number = parseInt(detail.number) - 1;
                  }
                  return detail;
                })
              }),
            1000
          );
        } else if (this.state.type === true) {
          clearInterval(myTimer);
        }
      };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM