第一次没有延迟地执行setInterval函数 [英] Execute the setInterval function without delay the first time
问题描述
有一种方法可以配置javascript的 setInterval
方法立即执行该方法,然后使用计时器执行
It's there a way to configure the setInterval
method of javascript to execute the method immediately and then executes with the timer
推荐答案
第一次直接自己调用函数是最简单的:
It's simplest to just call the function yourself directly the first time:
foo();
setInterval(foo, delay);
但是有充分的理由避免 setInterval
- 特别是在某些情况下, setInterval
事件的整个负载可以在没有任何延迟的情况下立即到达。另一个原因是如果你想要停止循环,你必须显式调用 clearInterval
,这意味着你必须记住从原始 setInterval <返回的句柄/ code> call。
However there are good reasons to avoid setInterval
- in particular in some circumstances a whole load of setInterval
events can arrive immediately after each other without any delay. Another reason is that if you want to stop the loop you have to explicitly call clearInterval
which means you have to remember the handle returned from the original setInterval
call.
所以另一种方法是让 foo
触发自己以便后续使用 setTimeout
而是:
So an alternative method is to have foo
trigger itself for subsequent calls using setTimeout
instead:
function foo() {
// do stuff
// ...
// and schedule a repeat
setTimeout(foo, delay);
}
// start the cycle
foo();
这可以保证至少的间隔在呼叫之间延迟
。如果需要,它还可以更容易地取消循环 - 当你的循环终止条件达到时,你只需要调用 setTimeout
。
This guarantees that there is at least an interval of delay
between calls. It also makes it easier to cancel the loop if required - you just don't call setTimeout
when your loop termination condition is reached.
更好的是,您可以将所有内容包装在立即调用的函数表达式中,该函数表达式会创建函数,然后再按上面的方式自行调用,并自动启动循环:
Better yet, you can wrap that all up in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:
(function foo() {
...
setTimeout(foo, delay);
})();
定义函数并一次性开始循环。
which defines the function and starts the cycle all in one go.
这篇关于第一次没有延迟地执行setInterval函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!