错误提示:TypeError: Cannot read property ‘setInterval’ of undefined
原因:用了window.setInterval(“InsertAutoPage();”,1000);

在webapp开发中貌似不能直接用window.setInterval…包括document.getElementById(“RemainingTimeId”);这种也不行。只有在浏览器端调试可以,但在真机上运行就会出错。

uni-app 中正确使用定时器和清除定时器

1、 定义一个timer

data(){
    return{
        timer: null
    }
}

2、设置定时器

//选择适合需求的定时器
this.timer = setTimeout( () => {
    // 这里添加您的逻辑		
}, 1000)
this.timer = setInterval( () => {
    // 同上			
}, 1000)

3、清除定时器
这里需要注意的是我们页面中使用了定时器,在离开这个页面的时候一定要记得清除,避免出现bug。
一般页面用onUnload

onUnload() {
	if(this.timer) {  
		clearTimeout(this.timer);  
		this.timer = null;  
	}  
}

tabbar页面用onHide

onHide() {
	if(this.timer) {  
		clearTimeout(this.timer);  
		this.timer = null;  
	}  
}

参考博客

1、uni-app 中使用定时器和取消定时器
2、webapp 慎用setInterval、setTimeout
3、uniapp官方文档解释
4、uni-app 在真机上运行 没有window对象

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐