js通用倒计时代码

2018-12-03 | 29浏览 | 0评论 | 标签:倒计时

js通用倒计时代码

一段通用的js倒计时代码,写这里备忘。

源码

var countDown = function (opts) {
  var from = (opts.from ? new Date(opts.from) : new Date()).getTime(),
    to = new Date(opts.to).getTime(),
    timeUp = false,
    between = to - from,
    timer = null,
    fix0 = function (num) {
      return num < 10 ? ('0' + num) : num
    },
    timerFn = function () {
      var d, h, m, s;
      if (between > 0) {
        d = fix0(Math.floor(between / 1000 / 60 / 60 / 24));
        h = fix0(Math.floor(between / 1000 / 60 / 60 % 24));
        m = fix0(Math.floor(between / 1000 / 60 % 60));
        s = fix0(Math.floor(between / 1000 % 60));
        between -= 1000;
        timeUp = false;
      } else {
        d = '00';
        h = '00';
        m = '00';
        s = '00';
        between = 0;
        timeUp = true;
        timer && clearInterval(timer);
      }
      typeof opts.callback == 'function' && opts.callback({ d: d, h: h, m: m, s: s, timeUp: timeUp })
    };
  timerFn();
  timer = setInterval(timerFn, 1000);
}

调用方法

countDown({
   from: '2018/12/3 00:00:00', //开始时间(留空取当前时间)
   to: '2018/12/30 00:00:00',  //结束时间
   callback: function (res) {  //回调(每秒一次)
     console.log(res)  // => {d: 20, h: 00, m: 04, s: 09, timeUp: false}
   }
})

(本篇完。欢迎留言探讨, 或打赏支持。)

添加评论 (已启用人工审核)

打赏
编辑代码 运行结果
退出