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 @   龙卷风吹毁停车场  阅读(470)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-04-27 element 设置table表头样式
2020-04-27 js使用正则表达式匹配富文本框中的img标签
点击右上角即可分享
微信分享提示