javascript - 在 React.js 中自动重置计时器

标签 javascript reactjs timer

我在react.js 中重新启动计时器时遇到问题。我想要实现的是:当计时器达到某个值(如我的示例中的 f.ex 20)时,它会重新启动到 0 并自动继续,没有任何事件,自动再次计数。

提前谢谢您!

这是我的代码:

import React, { Component } from 'react';

require('../../sass/main.scss');

class TypeAnimation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sec: 0,

        };
    }
    componentDidMount() {
        this.textInterval = setInterval(() => {
            this.setState({
                sec: this.state.sec + 1
            });
        }, 100);
    }

    componentDidUpdate(prevProps, prevState) {
        if (this.state.sec === 20) {
              clearInterval(this.textInterval);
              this.firstTimeout = setTimeout(() => {
                this.setState({
                    sec: 0
                });
              }, 3000);
          }
        }

    render() {
        const inText = this.props.text[0];
        const firstLine = inText.substr(0, this.state.sec);


        return (
            <div>
                <h2>
                    {firstLine}
                    <span className='blinker'> | </span>
                </h2>
            </div>
        );
    }
}

export default TypeAnimation;

最佳答案

this.textInterval = setInterval(() => {
    this.setState(prevState => ({
       sec: prevState.sec < 20 ? prevState.sec + 1 : 0
    }));
}, 1000);

关于javascript - 在 React.js 中自动重置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48721596/

相关文章:

javascript - 如何从元素类中获取数据值?

javascript - 在命令行上运行 graphql 示例会导致意外的标记

javascript - 带有 AND OR 条件的 jquery 多个选择器

node.js - 使用 react js 和 express API 服务器使用 fetch 发布一个对象

java - 每 5 分钟生成一个位置

javascript - XLabs.Forms.Controls.HybridWebView 不显示 html/js 警报

javascript - React - Axios 正在将未定义的文件数据发送到 Node 服务器

javascript - 使用 Internet Explorer 进行 React-Redux trySubscribe 时出现错误(无法获取未定义的属性 "subscribe")

Java GUI 未加载

javascript - 即使页面刷新,如何使多个计时器不在 php 中重置?