帮助在 settimeout 和 setinterval 之间进行选择
更新 2:
好的,看起来它在一分钟后第一次运行。我如何让它在加载时运行,然后每分钟运行一次?
更新1:
我尝试过:var Interval = setInterval(get_reported_incidents, 60000);
但没有任何反应。在 get_reported_incidents();
中,我只有一个 alert("hello");
。
原始问题:
我想每分钟运行一个函数:
get_reported_incidents();
但我不确定哪种方法最适合此任务;
settimeout
或 setinterval
UPDATE 2:
OK, looks like it runs the first time after a minute. How do I get it to run onload, then every minute after that?
UPDATE 1:
I've tried: var interval = setInterval(get_reported_incidents, 60000);
but nothing happens. in get_reported_incidents();
I just have an alert("hello");
.
ORIGINAL QUESTION:
I want to run a function every minute:
get_reported_incidents();
But I am not sure which method is best for this task;
settimeout
or setinterval
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(7)
setinterval 以给定的时间间隔执行函数。 settimeout 在指定的等待时间后执行函数,然后退出。
如果您尝试每分钟执行一次类似 cron 的执行,您将需要使用 setinterval。
严格来说,setInterval()
是为重复事件而设计的,setTimeout()
是为一次性事件而设计的。
然而,您往往会发现,使用 setTimeout()
时间会逐渐“蠕动”。我没有以 1 分钟为间隔尝试过这种情况,但使用 1 秒计时器时,我发现这种情况发生了很多次。显示当前时间(精确到毫秒)的时钟将显示“现在”的毫秒值稳定增加。
请参阅 http://jsfiddle.net/alnitak/LJCJU/ 并调整间隔以了解我的意思!
因此,为了获得最大的准确性,我这样做:
var timerHandler = function() {
var interval = 60000;
// do some stuff
...
var now = new Date();
var delay = interval - (now % interval);
setTimeout(timerHandler, delay);
};
如果您希望计时器事件与系统上的时钟同步启动,而不是“大约每分钟”在某个未指定的时间启动,那么这是理想的选择。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这完全是个人喜好。
setInterval
有一些奇怪的边缘情况,当上一个间隔的代码在下一个间隔开始之前尚未完成运行时会发生什么情况(如果您的间隔是每分钟; 每秒间隔一次,这有时会有点棘手)。我倾向于更喜欢链式
setTimeout
调用(其中每个调用都安排下一个),因为它们无法与您一起逃跑 - 您的代码始终必须明确地说“好吧,下次再给我回电。 ”但正确编写的代码应该适用于其中任何一个。链式
setTimeout
调用也更适合异步操作,例如通过 ajax 轮询某些内容,因为在 ajax 操作完成之前您不会安排下一次超时。完成。使用setInterval
,因为ajax调用是异步的,所以最终可能会重叠它们。It's totally personal preference.
setInterval
has some odd edge cases around what happens when the previous interval's code hasn't finished running before the next interval is due to start (not a problem if your interval is every minute; intervals every second, which one sometimes wants, get a bit tricky).I tend to prefer chained
setTimeout
calls (where each schedules the next) because they can't run away with you — your code always has to explicitly say "Okay, and call me back again next time." But properly-written code should work with either.Chained
setTimeout
calls are also more well-suited to asynchronous operations, like for instance polling something via ajax, because you don't schedule the next timeout until the ajax operation completes. UsingsetInterval
, because the ajax calls are asynchronous, you could end up overlapping them.