问题描述
我需要一个倒数倒数计时器,它以秒为单位,以天,小时,分钟,秒和毫秒(最多两位数,零到100毫秒)的形式返回。
I need a reverse countdown timer that takes the time in seconds and returns in the form of day, hour, minute, second, and milliseconds (up to two digits, zero to 100 milliseconds).
由于延迟,下面的代码有时差。另外,10毫秒占用大量的CPU来调用定时器,可能是什么造成的?
My code below has a time difference because of the delay. Also, ten milliseconds occupy a large amount of CPU to call the timer, what could be causing this?
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)
}
推荐答案
如果你能提供更多信息,我可以给你一个更好的交流ent。
if you could provide more information I could give you a better comment.
但在我自己的项目中,我制作了一个TimerCountdown.js文件并在其中编写了以下代码:
But in my own project, I made a TimerCountdown.js file and wrote the code below in it:
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;
工作正常且根本没有泄漏(诀窍就是让这个组件成为一个单独的文件,所以当它更新时,它不会影响项目的其余部分。)
which is working fine and is not leaking at all(the trick is just making this component a seperate file, so when it updates, it doesn't affect the rest of the project).
我在项目的其他js文件中使用了如下组件:
I used this component like below in other js files of project:
<TimerCountdown initialTime={60}/>
您可以在 this.state.timer上应用所需的配置
并从中获得所需的结果。
you can apply your desired configuraion on the this.state.timer
and get your desired result out of it.
希望它可以帮到你。
这篇关于以毫秒为单位反应本机倒计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!