移动端经常会遇到点击获取短信验证码60s倒计时或者是秒杀活动的需求,对于日时分秒自己每次都得重新计算,于是自己就封装一个类似的功能,以后直接copy就行了。
var timer = null;
var t = 60;
countDown();
function countDown() {
timer = setInterval(function () {
//console.log(t);
var d = 0, h = 0, m = 0, s = 0;
if (t > 0) {
h = Math.floor(t / (60 * 60)) - (d * 24);
m = Math.floor(t / 60) - (d * 24 * 60) - (h * 60);
s = Math.floor(t) - (d * 24 * 60 * 60) - (h * 60 * 60) - (m * 60);
} else {
clearInterval(timer);
t = 60;
}
d < 10 ? "0" + d : d;
h < 10 ? "0" + h : h;
m < 10 ? "0" + m : m;
s < 10 ? "0" + s : s;
//console.log(h + ":" + m + ":" + s);
t--;
}, 1000)
}
网友评论