Skip to content
On this page
🎨 作者:Jacinda 📔 阅读量:

setInterval 定时器

这里主要是记录一下,之前项目中遇到的,也算比较简单的需求吧。

就是之前写页面获取当前时间的时候,用户反应时间没有一直更新,需要重新进一下才能获取最新的。

原因是写的时候,直接偷懒用了下面这行代码:

javascript
this.currentTime = this.$moment().format('HH:mm:ss')

既然要一直更新时间,那肯定就要用上定时器啦,每秒更新一下,但是涉及到定时器,就比较担心一直加载,影响页面性能,这就涉及到出页面的时候就要销毁定时器,这里就整理记录一下。

使用定时器的两种情况

  • 点击事件
  • 一进页面就开始使用
  • 在 keep-alive 中使用

点击事件

javascript
export default {
    data() {
        return {
            timer: null,// 初始定时器变量名为null
        };
    },
    methods: {
        start() {
            // 将定时器名字赋值到变量中
            this.timer = setInterval(() => {
                console.log("开始---");
            }, 1000);
        },
        end() {
            clearInterval(this.timer);
            // 清除定时器,回归默认值
            this.timer = null;
        },
    },
    beforeDestroy() {
        // 清除定时器
        clearInterval(this.timer);
    },
    // destroyed() {
    //     clearInterval(this.timer);
    // },
};

TIP

beforeDestroydestroyed 中都能 清除定时器

TIP

在离开这个页面的时候,(比如路由跳转到别的页面)必须要清除一下这个定时器,定时器不手动清除的话,会一直存在并执行,直到我们的项目服务停掉,或者关机。所以适当时候清除定时器是非常有必要的。不然耗费性能,且容易造成代码混乱。

一进页面就开始使用

如果是页面一进来就要执行定时器,可以在 mounted 钩子中写个定时器让其执行,注意要加上 if 判断,要把定时器清除掉。

原因:

  • 路由跳转,跳走了,就要清除这个定时器,所以在beforeDestroy钩子中要清除定时器

  • 关闭项目,关闭项目了以后,系统就会自动停掉定时器,这个不用管它

  • 刷新页面,这个时候vue组件的钩子是不会执行beforeDestroy和destroyed钩子的,所以需要加上if判断一下,若还有定时器的话,就清除掉

javascript
export default {
    data() {
        return {
            timer: null,// 初始定时器变量名为null
        };
    },
    mounted() {
        this.getDateTime();
        if (this.timer) {
            clearInterval(this.timer);
        } else {
            this.timer = setInterval(this.getDateTime, 1000);
        }
    },
    methods: {
        getDateTime() {
            // 获取当前时间
        },
    },
    beforeDestroy() {
        clearInterval(this.timer);
    },
}

在 keep-alive 中使用

如果使用了keep-alive包裹组件后,组件的生命周期就是如下:

  • 初始进入组件离开 created ---> mounted ---> activated --> deactivated
  • 后续进入和离开 activated --> deactivated

项目中写的时候,就是因为底层页面包裹路由时,用了 keep-alive,防止页面再次加载,节省时间。所以切换路由的时候,如果按照上述的情况写法,定时器并不会被销毁。

解决办法:

activated 中,开启定时器;
deactivated 中,销毁;

javascript
export default {
    data() {
        return {
            timer: null,// 初始定时器变量名为null
            currentDate: '', // 当前日期
			currentTime: '', // 当前时间
        };
    },
    created() {
        this.currentDate = this.$moment().format('YYYY-MM-DD');
    },
    activated() {
        if (this.timer) {
            clearInterval(this.timer);
        } else {
            this.timer = setInterval(this.getDateTime, 1000);
        }
    },
    deactivated() {
        clearInterval(this.timer);
        this.timer = null;
    },
    methods: {
        getDateTime() {
            var date = new Date();
            var hour = date.getHours();
            var minutes = date.getMinutes();
            var second = date.getSeconds();
            this.currentTime = this.check(hour) + ":" + this.check(minutes)+ ":" + this.check(second);
        },
        //判断时间是否为个位数,如果时间为个位数就在时间之前补上一个“0”
        check(val) {
            if (val < 10) {
                return ("0" + val);
            } 
            else {
                return (val);
            }
        },
    }
}

📖 参考文档