在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>
复制代码

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

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

相关文章
相关标签/搜索