每60秒调用一次函数 [英] Calling a function every 60 seconds
问题描述
使用 setTimeout()
可以在指定的时间启动一个函数:
setTimeout(function,60000);
但是如果我想多次启动该函数呢?每当一段时间间隔过去时,我想执行该函数(每60秒,假设)。 解决方案
如果你如果 timer
中的代码可能比您的时间间隔更长,请不要在乎
setInterval(function,delay)
这个函数触发了作为第一个参数反复传入的函数。
更好的方法是使用 setTimeout
以及自动执行的匿名
函数:
(function(){
//做一些东西
setTimeout(arguments.callee,60000);
})();
保证下一次调用不会在代码执行之前完成。在本例中,我使用 arguments.callee
作为函数参考。在 setTimeout
中给这个函数一个更好的方法,因为
Using setTimeout()
it is possible to launch a function at a specified time:
setTimeout(function, 60000);
But what if I would like to launch the function multiple times? Every time a time interval passes, I would like to execute the function (every 60 seconds, let's say).
If you don't care if the code within the timer
may take longer than your interval, use setInterval()
:
setInterval(function, delay)
That fires the function passed in as first parameter over and over.
A better approach is, to use setTimeout
along with a self-executing anonymous
function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
that guarantees, that the next call is not made before your code was executed. I used arguments.callee
in this example as function reference. It's a better way to give the function a name and call that within setTimeout
because arguments.callee
is deprecated in ecmascript 5.
这篇关于每60秒调用一次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!