帮助在settimeout和setinterval之间选择

帮助在settimeout和setinterval之间选择

本文介绍了帮助在settimeout和setinterval之间选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新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?

更新1:

我尝试过:var interval = setInterval(get_reported_incidents, 60000);,但是什么也没有发生.在get_reported_incidents();中,我只有一个alert("hello");.

I've tried: var interval = setInterval(get_reported_incidents, 60000); but nothing happens. in get_reported_incidents(); I just have an alert("hello");.

原始问题:

我想每分钟运行一个函数:

I want to run a function every minute:

get_reported_incidents();

但是我不确定哪种方法最适合此任务;

But I am not sure which method is best for this task;

settimeoutsetinterval

推荐答案

这完全是个人喜好. setInterval有一些奇怪的边缘情况,说明在下一个间隔开始之前,上一个间隔的代码尚未完成运行时会发生什么情况(如果间隔是每分钟,则不是问题;间隔是每秒,有时会有些棘手).

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).

我倾向于使用链式setTimeout通话(每个通话安排下一个通话),因为它们无法与您逃脱–您的代码总是必须明确地说好,下次再打给我".但是正确编写的代码都可以使用.

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.

链式setTimeout调用也更适合异步操作,例如通过ajax轮询某些内容,因为在ajax操作完成之前,您不会安排下一次超时.使用setInterval,因为ajax调用是异步的,所以最终可能会使它们重叠.

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. Using setInterval, because the ajax calls are asynchronous, you could end up overlapping them.

这篇关于帮助在settimeout和setinterval之间选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:02