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

9791228-e096f3709c2d1bee.png

WXML

{{day}}天{{hour}}时{{minute}}分{{second}}秒

JS

  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)
    })
  },


微信小程序 Utils丨SetInterval 实现倒计时_第1张图片

你可能感兴趣的:(微信小程序 Utils丨SetInterval 实现倒计时)