在vue组件中设置定时器和清除定时器

由于项目中难免会碰到需要实时刷新,无论是获取短信码,还是在支付完成后轮询获取当前最新支付状态,这时就需要用到定时器。
但是,定时器如果不及时合理地清除,会造成业务逻辑混乱甚至应用卡死的情况,这个时就需要清除定时器。
某个页面中启动定时器后,一定要在页面关闭时将定时器清除掉。即在页面卸载(关闭)的生命周期函数里,清除定时器。

<template>
    <view>
        <button @click="getStatus">{{ buttonText }}</button>
    </view>
</template>
<script>
    export default {
        data() {
            return {
                timer: null, //首先我在data函数里面进行定义定时器名称:
                buttonText : '轮询获取订单支付状态',
                timerNum: 60 // 设置定时器时间
            }
        },
        methods: {
            getStatus() {
                this.loading(); // 启动定时器
                this.timer = setInterval(() => {  //创建定时器
                    if (this.timerNum === 0) { // 设置的定时器时间为0后执行的操作
                        this.timer && this.clearTimer(); // 关闭定时器
                        window.open('https://nav.imaring.com/', '_blank'); // 在新窗口打开程序员网址导航
                    } else {
                        this.loading();
                    }
                }, 1000);
            },
            loading() { // 启动定时器
                this.timerNum -= 1; // 定时器减1
                this.text = '获取中(' + this.timerNum + ')';
            },
            clearTimer() {//清除定时器
                clearInterval(this.timer);
                this.timer = null;
            }
        },
        // 最后在beforeDestroy()生命周期内清除定时器:
        beforeDestroy() {
            clearInterval(this.timer);        
            this.timer = null;
        }
    }
</script>

小编推荐:程序员网址导航

作为一名码农,随着平时工作的需要,这里收集了国内外很多优秀网站,这其中包括在线工具、在线运行、免费接口、在线资源、在线学习、技术论坛、技术博客等等,满足一般程序员日常需求。

posted @ 2019-11-27 16:29  imaring  阅读(5159)  评论(0编辑  收藏  举报