每 60 秒调用一次函数 [英] Calling a function every 60 seconds
问题描述
使用 setTimeout()
可以在指定的时间启动一个函数:
Using setTimeout()
it is possible to launch a function at a specified time:
setTimeout(function, 60000);
但是如果我想多次启动该功能怎么办?每次经过一个时间间隔,我想执行该函数(假设每 60 秒一次).
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).
推荐答案
如果您不关心 timer
中的代码是否可能比您的间隔时间更长,请使用 setInterval()
:
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.
更好的方法是,将 setTimeout
与 自执行匿名
函数一起使用:
A better approach is, to use setTimeout
along with a self-executing anonymous
function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
这保证,在您的代码执行之前不会进行下一次调用.我在这个例子中使用了 arguments.callee
作为函数引用.这是给函数一个名称并在 setTimeout
内调用它的更好方法,因为 arguments.callee
在 ecmascript 5 中已被弃用.
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屋!