根据当前时间计算倒计时,在列表中计算倒计时

文章展示了如何使用JavaScript编写一个倒计时功能,特别是在一个类似拼夕夕的拼团活动中。代码包括单个倒计时的实现以及在列表中为每个项目显示倒计时的方法,利用setInterval进行更新,并在倒计时结束后清除定时器。此外,还讨论了在列表渲染中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在写一个类似拼夕夕拼团的活动,就几个人付相同的钱,即可成团。这就需要一个倒计时,来计算活动结束时间

代码如下:

            var that = this;
            var h,m,s,t;
            var leftTime =that.classInfo.countdown;  //这个时间是倒计时的毫秒数,我这里是由后台返的,也可自行计算(既活动结束时间转化成毫秒减去当前时间转化成毫秒),若为负数或者为0,则当前倒计时结束
            console.log(leftTime);
            that.cxtimer = setInterval(function () {
                leftTime--;
                if (leftTime>0){
                    h = Math.floor(leftTime/60/60/24);
                    m = Math.floor(leftTime/60/60) - h*24;
                    s = Math.floor(leftTime/60 - h*24*60 - m*60);
                    t = Math.floor(leftTime - s*60 - m*60*60 - h*24*60*60)
                        // console.log(h,m,s)
                    that.cxh = h<10?'0'+h:h;//这里是天,时,分,秒,等
                    that.cxm = m<10?'0'+m:m;
                    that.cxs = s<10?'0'+s:s;
                    that.cxt = t<10?'0'+t:t;
                    // console.log(that.cxh);
                }
                if(Number(leftTime)<=1){
                    that.cxh = '00'
                    that.cxm = '00'
                    that.cxs = '00'
                    that.cxt = '00'
                    clearInterval(that.cxtimer);
                }
            }.bind(that),1000)

  如果在一个列表中展示倒计时,该如何实现呢,代码如下:

   timer() { //页面多个定时器 //主要逻辑都在这页面更新
                let that = this;
                that.list = that.classInfo.order;//这是需要展示倒计时的列表
                var listtime= that.listtime;
                for(var i=0;i<that.list.length;i++){
                    that.listtime[i] = ''
                    var item = that.list[i];
                    that.timeradd(item,i,1);
                }
        },

  timeradd(item,i){
            var that = this;
            var h,m,s,t,rens;
            var leftTime = item.countdown;//列表中每一项的倒计时
            that.timergroup = setInterval(function () {
                leftTime--;
                if (leftTime>0){
                    h = Math.floor(leftTime/60/60/24);
                    m = Math.floor(leftTime/60/60) - h*24;
                    s = Math.floor(leftTime/60 - h*24*60 - m*60);
                    t = Math.floor(leftTime - s*60 - m*60*60 - h*24*60*60);
                    rens = h+'天'+m+'时'+s+'分'+t+'秒';
                }else{
                    rens = '0天0时0分0秒';
                    clearInterval(that.timergroup);
                }
                  that.listtime[i] = rens;
                that.$forceUpdate()//强制刷新数据
                }.bind(that),1000)

        },

以上即是倒计时的写法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值