倒计时通用方法

直接上两个函数

/**
 * 时间倒计时
 * 将倒计时字符串传递给回调函数
 * @author LiuChuanWei
 * @time 2018-08-15
 * @param 
 *         endTime 截止时间,单位毫秒
 *        format 字符串格式化,比如 d天h小时m分钟s秒
 *        callback 回调函数,format格式化后的字符作为参数传递给该回调函数
 */
function countdown(endTime, format, callback) {
    var nowTime = new Date().getTime();    
    var total_micro_second = endTime - nowTime || 0;   //单位毫秒
    if (total_micro_second < 0) {
        total_micro_second = 0;     // 时间初始化小于0,活动已结束状态
    }

    var clockStr = "已经截止";
    if (total_micro_second > 0) {
        clockStr = dateformat(total_micro_second, format)   // 格式化倒计时时钟字符串
        callback(clockStr);    // 回调自定义函数
        setTimeout(function () {
            total_micro_second -= 1000;
            countdown(endTime, format, callback);
        }, 1000)
    }
}

/**
 * 日期倒计时格式化
 * @author LiuChuanWei
 * @time 2018-08-15 
 * @param micro_second 单位毫秒, format 格式化字符串
 * @return 字符串
 *
 */
function dateformat(micro_second, format) {
    // 总秒数
    var second = Math.floor(micro_second / 1000);

    if (new RegExp("(d+)").test(format)) {
        // 天数
        var day = Math.floor(second / 3600 / 24);
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? day : ("00" + day).substr(("" + day).length));
        second = second % (3600 * 24);
    }

    if (new RegExp("(h+)").test(format)) {
        // 小时
        var hr = Math.floor(second / 3600);
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? hr : ("00" + hr).substr(("" + hr).length));
        second = second % 3600;
    }

    if (new RegExp("(m+)").test(format)) {
        // 分钟
        var min = Math.floor(second / 60);
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? min : ("00" + min).substr(("" + min).length));
        second = second % 60;
    }

    if (new RegExp("(s+)").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? second : ("00" + second).substr(("" + second).length));
    }
    return format;
}
View Code

 

那么,如何使用该倒计时函数呢?如下

(在微信小程序中使用)

// (单个)倒计时
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
        })
    })
}

 

posted @ 2018-08-15 11:37  刘一二  阅读(486)  评论(0编辑  收藏  举报