javascript setInterval 的更改间隔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15091059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:27:19  来源:igfitidea点击:

Change interval of setInterval

javascript

提问by SF.

Is there a way of modifying the interval of calls of function set with setInterval during runtime, other than removing it (clearInterval) and reinstating again with a different value?

除了删除它(clearInterval)并使用不同的值再次恢复之外,有没有办法在运行时修改使用 setInterval 设置的函数的调用间隔?

回答by oleq

Use setTimeout instead, additionally this a non-blocking method for async JS:

使用 setTimeout 代替,另外这是异步 JS 的非阻塞方法:

var interval = 1000;

function callback() {
   console.log( 'callback!' );
   interval -= 100; // actually this will kill your browser when goes to 0, but shows the idea
   setTimeout( callback, interval );
}

setTimeout( callback, interval );

Don't use setInterval, as in some cases (lots of setInterval+ long callbacks, which are usually longer than timeout), due to limited queue size, some callbacks will be dropped by the browser and never executed. Only setTimeoutguarantees execution.

不要使用setInterval,因为在某些情况下(很多setInterval+长的回调,通常比超时长),由于队列大小有限,一些回调将被浏览器丢弃并且永远不会执行。只setTimeout保证执行。

回答by Phrogz

Nope; removing the interval and re-adding it is the way to do it if you've used setInterval().

不; 如果您使用过setInterval().

You could accomplish the same goal of a varying timeout, however, by calling setTimeout()repeatedly with a variable delay at the end.

但是,您可以通过setTimeout()在最后以可变延迟重复调用来实现不同超时的相同目标。

Out of curiosity, what are you doing that you want to modify the interval? Perhaps requestAnimationFrame()might be more appropriate?

出于好奇,您在做什么要修改间隔?或许requestAnimationFrame()更合适?