避免setTimeOut循环多个实例

时间:2017-11-26 17:58:45

标签: javascript jquery

我有这样的功能:

https://jsfiddle.net/pjngaffo/1/

i=0;
function refreshInfos() {
    if($('.main_dialog').length > 0) {
            console.log('loop-->',i++);
        setTimeout(function(){refreshManager()},1000);
    }
}

$('.main_dialog').on('click',function(){
    refreshInfos();
});

function refreshManager(){
//do stuff
//then call refreshInfos() for automatisation purposes
refreshInfos();
}

如您所见,如果我点击按钮"请点击 - > console" 函数refreshInfos()有多个实例。

我的问题是,如何调用该函数(我需要的任何地方)使其他实例停止/销毁?

2 个答案:

答案 0 :(得分:1)

正如@priyadarshi swain所述,您需要使用clearTimeout()

1st:setTimeout()保存到全局变量,以便稍后清除计时器

第二名:创建另一个停止计时器的功能,并将i变量重置为0

第3名你需要在运行计时器功能之前始终调用停止计时器功能

以下是你如何做到这一点

var i = 0 , timer = 0;   // set timer as a global variable
function refreshInfos() {
    if($('.main_dialog').length > 0) {
        console.log('loop-->',i++);
        timer = setTimeout(function(){refreshManager()},1000);  // save it to timer variable
    }
}

// another function to stop the timer
function StoprefreshInfos(){ 
  clearTimeout(timer);  // clear the timer
  i = 0;   // reset i variable to 0
}
$('.main_dialog').on('click',function(){
  StoprefreshInfos();  // run the stop timer function before refresh info function
  refreshInfos();  // then run the refresh info function
});

// button click to just test and stop the timer
$('.stop').on('click',function(){
  StoprefreshInfos();  // stop the timer function
});

function refreshManager(){
//do stuff
//then call refreshInfos() for automatisation purposes
refreshInfos();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='main_dialog' style="border:1px solid #333">

  click -> console

</div>
<div class='main_dialog' style="border:1px solid #333">

  click -> console

</div>
<button class="stop">Stop Timer</button>

  

注意:,而refreshInfos();refreshManager()内运行,而您正在使用setTimeout(function(){refreshManager()},1000);这个   代码将刷新refreshInfos();所以我没有找到一个好方法   清除refreshInfos();函数中的计时器..而不是我   创建另一个函数来停止计时器

答案 1 :(得分:0)

使用window.clearTimeout()来停止执行。

 var timeout = setTimeout(function(){refreshManager()},1000); 
 window.clearTimeout(timeout);