Temporary changing the time of setInterval

我怕爱的太早我们不能终老 提交于 2019-12-08 09:33:42

问题


The timing value in setInterval determines the next time at which the function is going to be invoked again. For example:

t = 8000;    
myFunction(){
   if (someCondition){
        //halt setInterval
        //t = 5000;
       // setInterval(myFunction,t);
   }
    // do some logic
}

setInterval(myFunction, t);

The problem is changing of t will not affect the time that I want the current call to be remained before the next call. In other words, is there any way to halt setInterval and then I can reset it again with new time?


回答1:


If you want to do something like that, you're better off doing your own interval control with setTimeout.

var shortInterval = 2000, longInterval = 4000;

function timerCode() {
  // do something
  if (whatever) {
    setTimeout(timerCode, shortInterval);
  }
  else {
    setTimeout(timerCode, longInterval);
  }
}

setTimeout(timerCode, longInterval);

That way, on each iteration of the timer you can decide how long it should be until the next iteration. If you want to stop, just don't reset the timer at all.




回答2:


You have to use clearInterval().

    var myInterval = setInterval(myFunction, t);

    ...

    clearInterval(myInterval);

...

myInterval = setInterval(myFunction, 1000);


来源:https://stackoverflow.com/questions/19801278/temporary-changing-the-time-of-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!