在我的应用程序中,我发现一些JavaScript代码使用 setInterval ,时间为0毫秒,如下所示:
In my application I found some JavaScript code that is using setInterval with 0 milliseconds, like so:
self.setInterval("myFunction()",0);显然,这对我来说似乎不是一个好主意。任何人都可以告诉我这里的 setInterval 的行为是什么? (myFunction对服务器进行AJAX调用)
Obviously, this does not seem like a good idea to me. Can anyone tell me what will be the behaviour of setInterval here? ("myFunction" makes an AJAX call to the server)
我问这个是因为我在我的应用程序中有不正常的行为。 90%的情况下,应用程序运行正常,并且只对服务器进行一次调用。但有时会对服务器进行多次调用(到现在为止,最多只有48次调用),我几乎可以肯定这是这行代码的错误。
I am asking this because I am having an irregular behaviour in my application. 90% of the times, the application behaves correctly and exactly one call to the server is made. However sometimes, multiple calls are made to the server (until now, maximum is 48 calls) and I am almost certain it is the fault of this line of code.
推荐答案浏览器为间隔设置最小值。通常10毫秒,但它可以取决于浏览器。这意味着尽可能快地重复这个。 W3C规范说4ms: http:// www .whatwg / specs / web-apps / current-work / multipage / timers.html #timers
Browser set a minimal value for the interval. Usualy 10ms, but it can depend on the browser. This means repeat this as fast as I'm possibly allowed. The W3C spec say 4ms : www.whatwg/specs/web-apps/current-work/multipage/timers.html#timers
这是正确的但可能揭示设计错误。
This is correct but probably reveal a design error.
编辑:顺便说一下,将字符串传递给setTimeout / setInterval是不好的做法,而是传递一个函数,因为javascript具有一等函数。
By the way, it is bad practice to pass a string to setTimeout/setInterval, pass a function instead as javascript has first class functions.
更多推荐
JavaScript中的setInterval()行为,0毫秒
发布评论