首页 > 解决方案 > 以毫秒为单位反应本机倒计时计时器

问题描述

我需要一个倒数计时器,它以秒为单位计时,并以天、小时、分钟、秒和毫秒(最多两位数,0 到 100 毫秒)的形式返回。

由于延迟,我下面的代码有时间差。另外,十毫秒调用定时器占用了大量的CPU,这可能是什么原因造成的?

componentDidMount(){

// get the timer in second then timer * 100 

this.interval = setInterval(() => {
  if (this.state.timer > 0){
    this.setState((prevState)=>({
      timer: prevState.timer -= 1,
      h: Math.floor(this.state.timer / 360000),
      m: Math.floor((this.state.timer % 360000) / 6000),
      s: Math.floor(((this.state.timer % 360000) % 6000) / 100) ,
      mili:Math.floor(((this.state.timer % 360000) % 6000) % 100)
     }));

  }else{

    clearInterval(this.interval)
  }

},10);



}

  componentWillUnmount(){

    clearInterval(this.interval)

}

标签: javascriptreact-nativesetintervalintervalscountdowntimer

解决方案


如果您能提供更多信息,我可以给您更好的评论。

但在我自己的项目中,我制作了一个 TimerCountdown.js 文件,并在其中编写了以下代码:

import React, { Component } from 'react';
import { View } from 'react-native';
import { RText } from '../../shared';

class TimerCountdown extends Component {
constructor(props) {
    super(props);
    this.state ={
        timer: props.initialTime
    }
  }

  componentDidMount(){
    this.interval = setInterval(
      () => this.setState((prevState)=> ({ timer: prevState.timer - 1 })),
      1000
    );
  }

  componentDidUpdate(){
    if(this.state.timer === 1){ 
      console.log("-------------------timer count down is leaking")
      clearInterval(this.interval);
      this.props.onTimerElapsed()
    }
  }

  componentWillUnmount(){
   clearInterval(this.interval);
   this.props.onTimerElapsed()
  }

  render() {
    return (
        <Text style={this.props.style}> {this.state.timer} </Text>
    )
  }
}

export default TimerCountdown;

它工作正常并且根本没有泄漏(诀窍只是让这个组件成为一个单独的文件,所以当它更新时,它不会影响项目的其余部分)。

我在项目的其他 js 文件中使用了这个组件,如下所示:

<TimerCountdown initialTime={60}/>

您可以在 上应用您想要的配置this.state.timer并从中获得您想要的结果。

希望对您有所帮助。


推荐阅读