javascript - 以毫秒为单位反应本机倒计时计时器
问题描述
我需要一个倒数计时器,它以秒为单位计时,并以天、小时、分钟、秒和毫秒(最多两位数,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)
}
解决方案
如果您能提供更多信息,我可以给您更好的评论。
但在我自己的项目中,我制作了一个 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
并从中获得您想要的结果。
希望对您有所帮助。
推荐阅读
- flutter - Flutter 中的函数
- angular-material - 如何监听 DatePicker 日期范围已更改
- php - 页面导航的 if 语句
- javascript - 如何解决 npm err 代码 elifecycle 错误?
- time-complexity - 特定循环的时间复杂度
- javascript - 角色列表命令发送对象而不是角色 discord.js
- powerbi-datasource - Business Central:如何使用 Power BI 从已过帐的销售发票行表中检索总收入(包括增值税)?
- apache-kafka - Kafka:错误关闭代理,因为 E:\kafka\data\kafka 中的所有日志目录都失败了 (kafka.log.LogManager)
- css - 如何通过断点扩展 Bootstrap 4 类
- javascript - 我在使用 Javascript 的 Whatsapp 共享中遇到问题