js通用倒计时代码
2018-12-03 | 3,721浏览 | 0评论 | 标签:倒计时
一段通用的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}
}
})
(本篇完。有疑问欢迎留言探讨)
热门文章
- 微信小程序“拍照识图”上线(62,981)
- YouTube评论翻译插件《油管评论翻译机》上线了(57,023)
- 基金助手--chrome浏览器插件(43,582)
- 拍照识别彩票结果在线工具(31,301)
- vue+tabs动态组件方案漫谈(25,957)
- 《油管评论翻译机》使用说明书(23,681)
- 网页打印插件Print.js(23,442)
- 自用YouTube抓取评论+翻译工具(22,649)
- px转rem/vw方法小结(17,416)
- YouTube评论导出免费在线工具(16,640)