倒计时的实现

var endTime = 1218154088; // 活动结束时间
var nowTime = 1215291843; // 当前时间

if (nowTime < endTime) {
    /**
     * 倒计时计算函数
     *
     * @param int endTime 结束时间戳
     * @param int nowTime 当前时间戳
     * @return string 剩余时间,格式:D天H小时M分S秒,数字小于10左侧不补零
     */
    var countDownCalculate = function (endTime, nowTime) {
        var day = 0;
        var hour = 0;
        var minute = 0;
        var second = 0;
        var surplusSecond = endTime - nowTime; // 剩余秒数
        if (surplusSecond > 0) {
            day = parseInt(surplusSecond / 60 / 60 / 24);
            hour = parseInt(surplusSecond / 60 / 60 % 24);
            minute = parseInt(surplusSecond / 60 % 60);
            second = parseInt(surplusSecond % 60);
        }
        return day + '天' + hour + '小时' + minute + '分' + second + '秒';
    }

    // 倒计时刷新函数,使用递归和setTimeout()实现
    function countDownRefresh() {
        var countDown = countDownCalculate(endTime, nowTime);
        console.log('活动剩余时间:' + countDown);

        if (nowTime >= endTime) {
            console.log('活动已结束');
        } else {
            nowTime++;
            setTimeout('countDownRefresh()', 1000);
        }
    }
    countDownRefresh();
} else {
    console.log('活动已结束');
}

Copyright © 2024 码农人生. All Rights Reserved