纯js倒计时

javascript 倒计时

最近项目中需要写个倒计时,就整理下…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var countDown = function(targetTime, callback) {

var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24,
timer;

function addZero(num) {
if (num < 10) {
return '0' + num;
}
return num;
}

function start() {
var endTime = new Date(targetTime).getTime(),
nowTime = new Date().getTime(),
timeDiff = endTime - nowTime,
data;

if (timeDiff <= 0) {
clearInterval(timer);
if (typeof callback === 'function') {
callback();
}
} else {
if (!timer) {
timer = setInterval(start, 1000);
}
}

data = {
'days': Math.floor(timeDiff / _day),
'hours': addZero(Math.floor((timeDiff % _day) / _hour)),
'minutes': addZero(Math.floor((timeDiff % _hour) / _minute)),
'seconds': addZero(Math.floor((timeDiff % _minute) / _second))
}

console.log('hours:' + data.hours + ',minutes:' + data.minutes + ',seconds:' + data.seconds);
}

start();
};

countDown('2016-06-12 14:58:00', function() {
console.log('do something');
});

注意坑!ios系统中,new Date(‘2016-06-12 12:23:34’).getTime() 为 NaN
简单的解决方法,写个替换函数,格式为 2016/06/12 12:23:34 即可

1
2
3
function parseTime(strDate) {
return new Date(strDate.replace(/-/g, '/')).getTime();
}