解决js中的setInterval清空定时器不管用问题
#代码知识 发布时间: 2026-01-12
使用场景:我在函数A中调用定时器函数,定时器是单独写的一个函数

原因:页面加载时我调用了1次函数A,然后又单独调用了一次定时器函数,导致调用了2次setInterval(),导致有setInterval_id有2个值。
通过打印定时器的值发现的问题。
clearInterval()只关闭了其中一个setInterval_id,另一个setInterval_id还会启动setInterval()。
解决方法:把单独调用的定时器函数去掉。
补充知识:js vue中setTimeout无法通过clearTimeout清除问题
在异步清除中,利用vue 中data存放setTimeout的标识进行清除时,无法清除。则需要在函数前加上window.即可
如window.setTimeout与window.clearTimeout
具体代码如下
精简后的代码。
环境为electron-vue 渲染进程异步获取主进程上html并渲染到页面、过程中需要有loading的显示。
setTimeout 与clearTimeout 未加window时,this.timeOutLoading事件总会被触发。
<template>
<div id="dev">
<el-tabs v-model="activeName" @tab-click="handleClick" v-loading="loading">
<el-tab-pane label="文档" name="first">
<div v-html="html"></div>
</el-tab-pane>
<el-tab-pane label="设置" name="second">
<v-devCard></v-devCard>
</el-tab-pane>
</el-tabs>
</div>
</template>
<script>
const {ipcRenderer:ipc} = require('electron');
export default {
data(){
return{
activeName: 'second',
html:'',
loading:false,
timeOutLoading:0
}
},
methods:{
handleClick(tab, event) {
if(tab.name == 'first' && this.loading == false){
if(this.timeOutLoading != 0){
window.clearTimeout(this.timeOutLoading);
}
this.html = "<div style='text-align:center; height:200px; line-height:200px;'>加载中...</div>";
this.loading = true;
this.timeOutLoading = window.setTimeout(() => {
if(this.loading == true){
this.loading = false;
this.html = "<div style='text-align:center; height:200px; line-height:200px;'>加载超时</div>";
}
}, 3000);
window.setTimeout(() => {
ipc.send("getPage");
}, 500);
}
}
},
mounted(){
ipc.on('getPage-reply', (event, arg) => {
if(this.timeOutLoading != 0){
window.clearTimeout(this.timeOutLoading);
this.timeOutLoading = 0;
}
this.loading = false;
this.html = arg;
});
}
}
</script>
以上这篇解决js中的setInterval清空定时器不管用问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
代码知识SEO上一篇 : IDEA+GIT使用入门图文详解
下一篇 : Map与WeakMap类型在JavaScript中的使用详解
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!