js实现天小时分钟秒倒计时

实现倒计时功能

直接上代码

// 计算时间
countDown: function (time) {
  var date2
  var date1
  var self = this
  window.requestAnimationFrame(step)
  function step() {
    date1 = new Date().getTime(); //开始时间
    if (date2 == undefined) {
      date2 = new Date().getTime() + time; //结束时间
    }

    var date3 = date2 - date1; //时间差的毫秒数      
    //计算出相差天数
    var days = Math.floor(date3 / (24 * 3600 * 1000))
    //计算出小时数
    var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    var hours = self.zeroFill(Math.floor(leave1 / (3600 * 1000)))
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
    var minutes = self.zeroFill(Math.floor(leave2 / (60 * 1000)))
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
    var seconds = self.zeroFill(Math.round(leave3 / 1000))
    let temptime = self.time = days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒"
    if (temptime == '1天00小时00分钟00秒') {
      self.time = '24小时00分钟00秒'
    } else {
      self.time = temptime.substring(temptime.length - 11, temptime.length)
    }
    if (self.time.substring(9, 10) == 0 && self.time.substring(8, 9) == 6) {
      self.timeObj.sOne = 9
      self.timeObj.sTwo = 5
    } else {
      self.timeObj.sOne = self.time.substring(9, 10)
      self.timeObj.sTwo = self.time.substring(8, 9)
    }
    self.timeObj.mOne = self.time.substring(5, 6)
    self.timeObj.mTwo = self.time.substring(4, 5)
    self.timeObj.hOne = self.time.substring(1, 2)
    self.timeObj.hTwo = self.time.substring(0, 1)
    if (self.time == '00小时00分钟00秒') {
      console.log('时间到')
      return
    } else {
      window.requestAnimationFrame(step)
    }
  }
},
zeroFill: function (num) {
  num = '' + num
  if (num.length == 1) {
    num = '0' + num
  }
  return num
},

运行时调用函数,参数传倒计时的毫秒数

  this.countDown(86400000) //时间初始化
复制代码

写的比较草率,有问题联系我。

转载于:https://juejin.im/post/5d0b1ff4e51d45595319e34c

猜你喜欢

转载自blog.csdn.net/weixin_33906657/article/details/93175769