刚好做到一个优惠券秒杀显示时间,倒计时时间,效果如下, 主要用到定时器 setInterval
思想:定义一个定时器,完成之后一定要再生命周期内销毁定时器
1.vue中使用,在 mounted 生命周期里定义一个计时器, beforeDestroy 销毁定时器
mounted(){
let _this = this
this.timerID = setInterval(() => {
this.useTime = _this.ShowCountDown(this.startTime,this.endTime)
},1000);
},
销毁定时器
beforeDestroy() {
if (this.timerID) {
clearInterval(this.timerID); // 在Vue实例销毁前,清除我们的定时器
}
},
具体根据后端返回的开始时间和结束时间算出倒计时 ShowCountDown()函数时间转换逻辑

2. react 中就生命周期改边, 赋值写法变化,其他无变化
componentDidMount(){
this.timerID = setInterval( () =>
this.ShowCountDown(this.props.startTime,this.props.endTime),1000
);
}
销毁定时器
componentWillUnmount(){
clearInterval(this.timerID);
}
剩下的计算时间逻辑和vue是一样的