JavaScript中的setInterval()行为,0毫秒 [英] setInterval() behaviour with 0 milliseconds in JavaScript

查看:620
本文介绍了JavaScript中的setInterval()行为,0毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我发现一些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.org / 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 : http://www.whatwg.org/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毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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