倒计时通用方法

直接上两个函数

 1 /**
 2  * 时间倒计时
 3  * @author LiuChuanWei
 4  * @time 2018-08-15
 5  * @param 
 6  *             endTime 截止时间,单位毫秒
 7  *             format 字符串格式化,比如 d天h小时m分钟s秒
 8  *             callback 回调函数
 9  */
10 function countdown(endTime, format, callback) {
11   var nowTime = new Date().getTime();    
12     var total_micro_second = endTime - nowTime || 0;   //单位毫秒
13   if (total_micro_second < 0) {
14         total_micro_second = 0;     // 时间初始化小于0,活动已结束状态
15   }
16 
17     var clockStr = "已经截止";
18     if (total_micro_second > 0) {
19         clockStr = dateformat(total_micro_second, format)   // 格式化倒计时时钟字符串
20         callback(clockStr);    // 回调自定义函数
21         setTimeout(function () {
22             total_micro_second -= 1000;
23             countdown(endTime, format, callback);
24         }, 1000)
25     }
26 }
27 
28 /**
29  * 日期倒计时格式化
30  * @author LiuChuanWei
31  * @time 2018-08-15 
32  * @param micro_second 单位毫秒, format 格式化字符串
33  * @return 字符串
34  *
35  */
36 function dateformat(micro_second, format) {
37     // 总秒数
38     var second = Math.floor(micro_second / 1000);
39 
40     if (new RegExp("(d+)").test(format)) {
41         // 天数
42         var day = Math.floor(second / 3600 / 24);
43         format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? day : ("00" + day).substr(("" + day).length));
44         second = second % (3600 * 24);
45     }
46 
47     if (new RegExp("(h+)").test(format)) {
48         // 小时
49         var hr = Math.floor(second / 3600);
50         format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? hr : ("00" + hr).substr(("" + hr).length));
51         second = second % 3600;
52     }
53 
54     if (new RegExp("(m+)").test(format)) {
55         // 分钟
56         var min = Math.floor(second / 60);
57         format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? min : ("00" + min).substr(("" + min).length));
58         second = second % 60;
59     }
60 
61     if (new RegExp("(s+)").test(format)) {
62         format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? second : ("00" + second).substr(("" + second).length));
63     }
64     return format;
65 }

那么,如何调用倒计时呢?如下在微信小程序中使用

// (单个)倒计时
countdown(endTime, 'd天h小时m分钟s秒', function(clockStr){
    that.setData({
        clock: clockStr
    });
});

// (批量)遍历倒计时
var endTimeList = endTimeList || [];
var endTimeStrArr = that.data.endTimeStrArr || [];
for (var i = 0; i < endTimeList.length; i++) {
    var endTimeStr = endTimeStrArr[i];    // 在回调函数中不能使用变量i,故将变量声明在外面
    countdown(endTimeList[i].getTime(), 'hh:mm:ss', function(clockStr){
        endTimeStr = clockStr;
        that.setData({
            endTimeStrArr: endTimeStrArr
        })
    })
}

猜你喜欢

转载自www.cnblogs.com/lhat/p/9480502.html
今日推荐