JavaScript:如何让setInterval()立即启动? [英] JavaScript: How to get setInterval() to start now?
问题描述
我使用 setInterval()
函数每隔20秒调用一次函数。但是,我注意到的一件事是它第一次 setInterval()
实际上调用函数是20秒(而不是 setInterval()
被调用)。这是我目前的解决方法:
I am using the setInterval()
function to call a function every 20 seconds. However, one thing I noticed is that it the first time setInterval()
actually calls the function is at 20 seconds (and not when setInterval()
is called). Here is my current workaround:
dothis();
var i = setInterval(dothis, 20000);
如果没有这个重复的代码,有没有办法实现这个目标?
Is there any way to achieve this without having this duplicate code?
推荐答案
您的方法是正常的方式。
Your method is THE normal way way of doing it.
如果反复出现这种情况,您可以创建一个实用程序函数,先执行处理程序然后设置间隔:
If this comes up over and over, you could make a utility function that would execute the handler first and then set the interval:
function setIntervalAndExecute(fn, t) {
fn();
return(setInterval(fn, t));
}
然后,在您的代码中,您可以这样做:
Then, in your code, you could just do this:
var i = setIntervalAndExecute(dothis, 20000);
这篇关于JavaScript:如何让setInterval()立即启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!