javascript setInterval [英] javascript setInterval

查看:122
本文介绍了javascript setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个问题。如果我以这种方式使用setInterval:

  setInterval('doSome();',60000); 

我确定 doSome()即使我在浏览器中更改选项卡,也会每60秒触发一次函数?

解决方案

将字符串传递给 setInterval 很好,是使用 setInterval 的两种方法之一,另一种是传递函数指针。它在任何方面都没有错,就像其他答案状态一样,但它没有那么高效(因为代码必须被重新解析),也不是为了你的目的。两者

  setInterval('doSome();',60000); //这将从全局范围运行doSome 
//在全局范围内

  setInterval(doSome,60000); //这从本地范围运行doSome 
//在全局范围内

是正确的,虽然他们有略有不同的含义。如果 doSome 对于某些非全局范围是本地的,则在同一范围内调用后者将运行本地 doSome 每隔60000ms。调用前一个代码将始终在全局范围内查找 doSome ,如果没有 doSome 函数,则会失败全局范围。



无论标签焦点如何,都会可靠地触发该功能,间隔为 至少 60000ms ,但通常由于间接费用和延误而略微增加。



所有浏览器将间隔值限制为至少一定值,以避免间隔过于频繁(我认为它至少是10毫秒或4毫秒或其他东西,我不能完全记住)。



请注意,有些浏览器(即将推出的Firefox 5是一款,但可能还有其他我不知道的事情)进一步钳制 setInterval 对于例如如果选项卡未聚焦,则为1000毫秒。 (参考


a question. If i use setInterval in this manner:

setInterval('doSome();',60000);

am i safe that the doSome() function is triggered every 60 seconds, even if I change the tab in a browser?

解决方案

Passing a string to setInterval is fine, and is one of two ways to use setInterval, the other is passing a function pointer. It is not wrong in any way like the other answers state, but it is not as efficient (as the code must be reparsed) nor is it necessary for your purpose. Both

setInterval('doSome();', 60000); // this runs doSome from the global scope
                                 // in the global scope

and

setInterval(doSome, 60000);      // this runs doSome from the local scope
                                 // in the global scope

are correct, though they have a slightly different meaning. If doSome is local to some non-global scope, calling the latter from within the same scope will run the local doSome at 60000ms intervals. Calling the former code will always look for doSome in the global scope, and will fail if there is no doSome function in the global scope.

The function will reliably be triggered, regardless of tab focus, at intervals of at least 60000ms, but usually slightly more due to overheads and delays.

All browsers clamp the interval value to at least a certain value to avoid intervals being too frequent (I think it's a minimum of 10ms or 4ms or something, I can't exactly remember).

Note that some browsers (the upcoming Firefox 5 is one, but there are probably others that I don't know of) further clamp setInterval drastically to e.g. 1000ms if the tab is not focused. (Reference)

这篇关于javascript setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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