JavaScript中的setInterval()行为,0毫秒

编程入门 行业动态 更新时间:2024-10-09 10:27:30
本文介绍了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 / 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毫秒

本文发布于:2023-05-31 13:59:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/393003.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JavaScript   setInterval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!