临时更改setInterval的时间 [英] Temporary changing the time of setInterval

查看:314
本文介绍了临时更改setInterval的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

setInterval 中的计时值确定下次再次调用该函数的时间。例如:

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);

问题是改变 t 不会影响我希望当前通话在下次通话前保留的时间。换句话说,有没有办法停止 setInterval ,然后我可以用新的时间再次重置它?

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?

推荐答案

如果你想做类似的事情,你最好用 setTimeout 来做你自己的间隔控制。

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.

这篇关于临时更改setInterval的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆