JavaScript倒计时实现

 1 /**
 2  * 倒计时函数
 3  * @param {String}} endTime 终止时间戳
 4  */
 5 const countDown = (endTime, callback) => {
 6     const end = endTime,
 7         now = new Date().getTime();
 8     let differ = end - now,
 9         hours, minutes, seconds;
10     if (differ >= 0) {
11         hours = Math.floor(differ / 1000 / 60 / 60 % 24);
12         minutes = Math.floor(differ / 1000 / 60 % 60);
13         seconds = Math.floor(differ / 1000 % 60);
14     }
15     callback({
16         h: hours,
17         m: minutes,
18         s: seconds
19     });
20     setTimeout(() => {
21         countDown(end, callback);
22     }, 1000);
23 };
24 
25 /**
26  * 时间前加零
27  * @param {Number} time
28  */
29 const check = time => {
30     if (time < 10) {
31         time = '0' + time;
32     }
33     return time;
34 };
35 
36 export default countDown;
1 countDown(new Date('2018/9/5 10:00:00'), function(timeObj) { // 调用
2       console.log(timeObj.h, timeObj.m, timeObj.s)
3 });

猜你喜欢

转载自www.cnblogs.com/ljwk/p/9583817.html