首页 > 其他 > 详细

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

时间:2019-11-27 16:44:15      阅读:86      评论:0      收藏:0      [点我收藏+]

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

<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>

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

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

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

原文:https://www.cnblogs.com/imaring/p/11943291.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!