短信验证码倒计时 H5页面锁屏或切入后台定时器不准确问题

468 阅读1分钟

// 在react下写的代码,
countDown = () => {  
    const oldTime = new Date().getTime() / 1000;  
    if (!this.timer) {   
        this.timer = setInterval(() => {   
            const { count } = this.state;     
            const newTime = new Date().getTime() / 1000;  // 获取系统当前时间
            const time = Math.round(newTime - oldTime);   // 算好时间差
            if (count > 0 && count <= 60) {  
                this.setState({     
                    count: 60 - time,         
                    disabled: true    
                })    
            } else {    
                clearInterval(this.timer);   
                this.timer = null;     
                this.setState({     
                    count: 60,       
                    disabled: false  
                });  
            }
        }, 1000); 
    }};

原文链接:blog.csdn.net/fendoudemay…