在setInterval / setTimeout中使用变量作为时间

这是一个示例情况。

var count, time = 1000; setInterval(function(){ count += 1; }, time); 

上面的代码将“count”var加1,非常1000毫秒。 似乎setInterval在被触发时将使用它在执行时看到的时间。 如果稍后更新该值,则不会考虑这一点,并将继续使用设置的初始时间触发。

如何动态更改此方法的时间?

使用setTimeout代替回调和变量而不是数字。

 function timeout() { setTimeout(function () { count += 1; console.log(count); timeout(); }, time); }; timeout(); 

在这里演示

更短的版本将是:

 function periodicall() { count++; setTimeout(periodicall, time); }; periodicall(); 

尝试:

 var count, time = 1000, intId; function invoke(){ intId = setInterval(function(){ count += 1; if(...) // now i need to change my time { time = 2000; //some new value intId = window.clearInterval(intId); invoke(); } }, time); } invoke(); 

您无法动态更改间隔,因为它已设置一次,然后您不会再次重新运行setInterval代码。 那么你可以做些什么来清除间隔并再次设置它运行。 你也可以使用类似逻辑的setTimeout ,但是使用setTimeout你需要每次都注册一个超时,你不需要使用clearTimeout除非你想在它们之间中止。 如果你每次都在改变时间,那么setTimeout更有意义。

 var count, time = 1000; function invoke() { count += 1; time += 1000; //some new value console.log('displ'); window.setTimeout(invoke, time); } window.setTimeout(invoke, time); 

你不能(据我所知)动态改变间隔。 我建议用回调来做到这一点:

 var _time = 1000, _out, _count = 0, yourfunc = function() { count++; if (count > 10) { // stop clearTimeout(_out); // optional } else { // your code _time = 1000 + count; // for instance _out = setTimeout(function() { yourfunc(); }, _time); } }; 

JavaScript中没有通过引用传递整数,这意味着无法通过更改变量来更改间隔。

只需取消setInterval并使用新时间重新启动它。

示例可以在这里找到: http : //jsfiddle.net/Elak/yUxmw/2/

 var Interval; (function () { var createInterval = function (callback, time) { return setInterval(callback, time); } Interval = function (callback, time) { this.callback = callback; this.interval = createInterval(callback, time); }; Interval.prototype.updateTimer = function (time) { clearInterval(this.interval); createInterval(this.callback, time); }; })(); $(document).ready(function () { var inter = new Interval(function () { $("#out").append("
  • " + new Date().toString() + "
  • "); }, 1000); setTimeout(function () { inter.updateTimer(500); }, 2000); });