微信小程序 Utils丨SetInterval 实现倒计时

2019-10-08 15:42:13 浏览数 (1)


WXML

代码语言:javascript复制
<text>{{day}}天{{hour}}时{{minute}}分{{second}}秒</text>

JS

代码语言:javascript复制
  onLoad: function (options) {
    that = this;
    that.countDown('2019-10-24 10:00:00');
  }
     
  /**
   * 倒计时
   * 
   * @param endTime 结束日期 时间
   * **/
  countDown:function(endTime){
    that.setData({
      timer: setInterval(function(){

        var downTime = parseInt(new Date(endTime.replace(/-/g, "/")).getTime() - new Date().getTime())
        
        // 倒计时结束
        if(downTime <= 0){
           that.setData({
             day: '00',
             hour: '00',
             minute: '00',
             second: '00'
           })
           clearInterval(that.data.timer);
           return;
        }

        var d = parseInt(downTime / 1000 / 3600 / 24);
        var h = parseInt(downTime / 1000 / 3600 % 24);
        var m = parseInt(downTime / 1000 / 60 % 60);
        var s = parseInt(downTime / 1000 % 60);

        d < 10 ? d = '0'   d : d;
        h < 10 ? h = '0'   h : h;
        m < 10 ? m = '0'   m : m;
        s < 10 ? s = '0'   s : s;

        that.setData({
          day: d,
          hour: h,
          minute: m,
          second: s
        })

      }, 1000)
    })
  },

0 人点赞