问题
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).
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)
}
回答1:
if you could provide more information I could give you a better comment.
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).
I used this component like below in other js files of project:
<TimerCountdown initialTime={60}/>
you can apply your desired configuraion on the this.state.timer
and get your desired result out of it.
Hope it help you.
来源:https://stackoverflow.com/questions/55275788/react-native-count-down-timer-in-millisecond