JavaScript:如何让 setInterval() 现在开始?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7424155/
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
JavaScript: How to get setInterval() to start now?
提问by Andrew
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:
我正在使用该setInterval()
函数每 20 秒调用一次函数。但是,我注意到的一件事是它第一次setInterval()
实际调用该函数是在 20 秒(而不是何时setInterval()
被调用)。这是我目前的解决方法:
dothis();
var i = setInterval(dothis, 20000);
Is there any way to achieve this without having this duplicate code?
有没有办法在没有这个重复代码的情况下实现这一目标?
回答by jfriend00
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);
回答by jyore
You can make an anonymous function and call it immediately, except you use the setTimeout function instead of setInterval.
您可以创建一个匿名函数并立即调用它,除非您使用 setTimeout 函数而不是 setInterval。
(function doStuff() {
//Do Stuff Here
setTimeout(doStuff,20000);
})();
This will execute the function, then call it again in 20 seconds.
这将执行该函数,然后在 20 秒内再次调用它。
Note that depending on the behavior you desire or in some cases for performance, it can be better to use setTimeout over setInterval. The main difference is that setInterval calls that function whenever that timeout is up, REGARDLESS if the last call has finished executing or if an error occurs. Using setTimeout is this fashion ensures that the function finishes its execution before the timer resets. A lot of the tradeoffs are pretty apparent, but it is a good thing to keep in mind as you design your application.
请注意,根据您想要的行为或在某些情况下的性能,最好使用 setTimeout 而不是 setInterval。主要区别在于 setInterval 在超时结束时调用该函数,如果最后一次调用已完成执行或发生错误,则不管。使用 setTimeout 这种方式可确保函数在计时器重置之前完成其执行。许多权衡是非常明显的,但在设计应用程序时牢记这一点是件好事。
EDITIn response to patrick dw's concern about having the need to cancel the timeout. The best solution is to not use the anonymous function, and just call it after declaration
编辑响应 patrick dw 对需要取消超时的担忧。最好的解决办法是不使用匿名函数,只在声明后调用
var timeout;
function doStuff() {
//doStuff
timeout = setTimeout(doStuff,20000);
}
doStuff()
Yes this is similar to what the OP was trying to avoid, but it does removes the need to call the function and then call the setInterval function, so you save a line of code. You can stop and start the function at anytime by:
是的,这与 OP 试图避免的情况类似,但它确实消除了调用该函数然后调用 setInterval 函数的需要,因此您可以节省一行代码。您可以通过以下方式随时停止和启动该功能:
//Stop it
clearTimeout(timeout);
//Start it
doStuff();
回答by user113716
If your dothis
function has no other need for a return value, you can have it return itself.
如果您的dothis
函数不需要返回值,您可以让它返回自身。
This will allow you to invoke and pass it at the same time. If the return value is otherwise ignored, it will be harmless.
这将允许您同时调用和传递它。如果返回值被忽略,它将是无害的。
function dothis() {
// your code
return dothis;
}
var i = setInterval(dothis(), 20000);
Otherwise, you could extend Function.prototype
to give an invoke and return functionality to all your functions:
否则,您可以扩展Function.prototype
为所有函数提供调用和返回功能:
DEMO:http://jsfiddle.net/ZXeUz/
演示:http : //jsfiddle.net/ZXeUz/
Function.prototype.invoke_assign = function() {
var func = this,
args = arguments;
func.call.apply( func, arguments );
return function() { func.call.apply( func, args ); };
};
setInterval( dothis.invoke_assign( 'thisArg', 1, 2, 3 ), 20000 );
// thisArg 1 2 3
// thisArg 1 2 3
// thisArg 1 2 3
// ...
This actually enhances things a bit. It lets you pass a set of arguments. The first argument will set the this
value of the function you're invoking, and the rest of the arguments will be passed on as the regular arguments.
这实际上增强了一些东西。它允许您传递一组参数。第一个参数将设置this
您正在调用的函数的值,其余参数将作为常规参数传递。
Because the function returned is wrapped in another function, you'll have identical behavior between the initial and interval invocations.
因为返回的函数被包装在另一个函数中,所以初始调用和间隔调用之间的行为是相同的。