0
点赞
收藏
分享

微信扫一扫

uniapp 之倒计时兼定时器代码及效果

有的时候我们可能有活动倒计时的需求,苦于没有思路;以下可直接套用 上代码

<view class="top_pay">请在{{countdown}}内支付</view>
data:{
    liveCountTimes:null // 声明定时器
}
getLiveTimeCount(stime) {
    // stime  结束时间(毫秒级时间戳)
    this.liveCountTimes = setInterval(() => {
        let nowTime = new Date().getTime();
        let preTime = stime;
        let obj = null;
        if (preTime - nowTime > 0) {
            let time = (preTime - nowTime) / 1000;
            let day = parseInt(time / (60 * 60 * 24));
            let hou = parseInt(time % (60 * 60 * 24) / 3600);
            let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
            let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
            obj = {
                day: day < 10 ? '0' + day : day,
                hou: hou < 10 ? '0' + hou : hou,
                min: min < 10 ? '0' + min : min,
                sec: sec < 10 ? '0' + sec : sec
            };
            this.liveCountdown = obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'
            this.$forceUpdate();  // 更新页面实时更新(重要不可省略)
            this.countobj = obj;
            
        } else {
            obj = {
                day: '00',
                hou: '00',
                min: '00',
                sec: '00'
            };
            this.countobj = obj;
            clearInterval(this.liveCountTimes)
        }
    }, 1000)
},
// 退出当前页面时清除定时器
onUnload(){
    clearInterval(this.liveCountTimes)
},


效果图 image.png

举报

相关推荐

0 条评论