您的位置:首頁技術文章
文章詳情頁

解決js中的setInterval清空定時器不管用問題

瀏覽:68日期:2024-04-12 13:00:21

使用場景:我在函數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清空定時器不管用問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: JavaScript
相關文章:
国产综合久久一区二区三区