每60秒调用一次函数 [英] Calling a function every 60 seconds

查看:397
本文介绍了每60秒调用一次函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 setTimeout()可以在指定的时间启动一个函数:

  setTimeout(function,60000); 

但是如果我想多次启动该函数呢?每当一段时间间隔过去时,我想执行该函数(每60秒,假设)。 解决方案

如果你如果 timer 中的代码可能比您的时间间隔更长,请不要在乎 setInterval(): p>

  setInterval(function,delay)

这个函数触发了作为第一个参数反复传入的函数。

更好的方法是使用 setTimeout 以及自动执行的匿名函数:

 (function(){
//做一些东西
setTimeout(arguments.callee,60000);
})();

保证下一次调用不会在代码执行之前完成。在本例中,我使用 arguments.callee 作为函数参考。在 setTimeout 中给这个函数一个更好的方法,因为 arguments.callee 在ecmascript 5中不推荐使用。


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆