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

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

<template>
    <div>
        <button @click="getStatus">{{ buttonText }}</button>
    </div>
</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://baidu', '_blank'); // 在新窗口打开百度页面
                    } else {
                        this.loading();
                    }
                }, 1000);
            },
            loading() { // 启动定时器
                this.timerNum -= 1; // 定时器减1
                this.text = '获取中(' + this.timerNum + ')';
                    (在这里写需要请求的api)
            },
            clearTimer() {//清除定时器
                clearInterval(this.timer);
                this.timer = null;
            }
        },
        // 最后在beforeDestroy()生命周期内清除定时器:
        beforeDestroy() {
            clearInterval(this.timer);        
            this.timer = null;
        }
    }
</script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。