vue实现倒计时

在assets下新建tool.js文件
function countDownFun(time) {
    time--;
    let nowTime = new Date().getTime(); // 获取当前时间
    if (time >= nowTime) {
        var secondTime = 0 //
        var minuteTime = 0; //
        var hourTime = 0; // 小时
        var today = 0 //// 全部剩余多少秒
        var seconds = Math.ceil((time - nowTime) / 1000)

        hourTime = Math.floor(seconds / 3600)
        //天数
        today = Math.floor(hourTime / 24)
        //小时
        hourTime = Math.floor(hourTime % 24) < 10 ? '0' + Math.floor(hourTime % 24) : Math.floor(hourTime % 24)
        //
        minuteTime = Math.floor(seconds / 60 % 60) < 10 ? '0' + Math.floor(seconds / 60 % 60) : Math.floor(seconds / 60 % 60)
        //
        secondTime = Math.floor(seconds % 60) < 10 ? '0' + Math.floor(seconds % 60) : Math.floor(seconds % 60)

        return today + 'd' + hourTime + 'h' + minuteTime + 'm'
    } else {
        return "00d 00h 00m";
    }
}

export function initCountdown(endTime, callback) {
    let time = '00d 00h 00m'
    let Interval = ''
    if (endTime - Date.now() > 0) {
        time = countDownFun(endTime); //首次
        //定时器
        Interval = setInterval(function () {
            if (endTime - Date.now() <= 0) {
                clearInterval(Interval);
                time = "00d 00h 00m";
            } else {
                time = countDownFun(endTime);
            }
            callback(time)
        }, 1000);
    } else {
        callback(time)
    }
}

在需要使用的地方引入 initCountdown

initCountdown('目标时间戳', (reslove)=>{
     this.time = reslove //返回的结果
})

 

posted @ 2023-04-27 10:30  龙卷风吹毁停车场  阅读(487)  评论(0)    收藏  举报