美文网首页
js实现计时器

js实现计时器

作者: 子夜照弦歌 | 来源:发表于2020-09-18 17:55 被阅读0次

    转载请注明出处

    业务场景:

    • 实现传入数值开始进行计时(日、时、分、秒)
    // data()
    showBtn: true,
    timeDay: 0,
    timeHour: 0,
    timeMinute: 0,
    timeSecond: 0,
    timer: null,
    socketTimer: null,
    
    // 格式化时分秒
    formatDate(date) {
        // 传入的时间为时间戳 (秒)
        // 先清除定时器
        if(this.timer){
            clearInterval(this.timer)
            this.timer = null;
        }
        // 获取当前时间,这是获取到的时间戳是到ms,所以这里要除1000
        var timestamp = Date.parse(new Date())  / 1000;
        let total = timestamp - date;
        var day = parseInt(total / (24 * 60 * 60)); //计算整数天数
        var afterDay = total - day * 24 * 60 * 60; //取得算出天数后剩余的秒数
        var hour = parseInt(afterDay / (60 * 60)); //计算整数小时数
        var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60; //取得算出小时数后剩余的秒数
        var min = parseInt(afterHour / 60); //计算整数分
        var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60; //取得算出分后剩余的秒数
        this.timeDay = day;
        this.timeHour = hour;
        this.timeMinute = min;
        this.timeSecond = afterMin;
        this.dateProceed()
    },
    // 获取已存在数值进行计时
    dateProceed() {
        let _this = this;
        this.timer = setInterval(function() {
            _this.timeSecond++;
            if (_this.timeSecond >= 60) {
                _this.timeMinute += 1;
                _this.timeSecond = 0;
            }
            if (_this.timeMinute >= 60) {
                _this.timeHour += 1;
                _this.timeMinute = 0;
            }
            if (_this.timeHour >= 24) {
                _this.timeDay += 1;
                _this.timeHour = 0;
            }
        }, 1000)
    },
    

    相关文章

      网友评论

          本文标题:js实现计时器

          本文链接:https://www.haomeiwen.com/subject/ldwjyktx.html