在一个页面中可以同时设置多少个 javascript setTimeout/ setInterval 调用?
我必须使用至少 2 个 setTimeouts 和 1 个 setInterval。这是否依赖于所使用的浏览器或 JavaScript 引擎?
I have to use atleast 2 setTimeouts and 1 setInterval. Does this have any dependency on the browser or javascript engine being used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
tl;dr:在创建 100K 个计时器之前,不要担心计时器的成本。
我刚刚通过创建此测试文件(一遍又一遍地创建 100K 计时器)对计时器性能进行了快速测试:
我在大约 2014 年 Macbook Pro 上的 Google Chrome (v54) 中打开了此文件,然后转到开发人员工具中的“时间轴”选项卡并记录页面加载时的内存配置文件并运行 3-4 个测试周期。
观察
计时器创建循环需要 200 毫秒。预测试页堆大小从 3.5MB 开始,最终稳定在 3.9MB。
结论
每个计时器的设置时间约为 0.002 毫秒,并向 JS 堆添加约 35 个字节。
tl;dr: Don't worry about the cost of timers until you're creating 100K's of them.
I just did a quick test of timer performance by creating this test file (creates 100K timers over and over):
I opened this file in Google Chrome (v54) on my circa ~2014 Macbook Pro, and went to the Timeline tab in Developer Tools and recorded the memory profile as the page loaded and ran thru 3-4 cycles of the test.
Observations
The timer creation loop takes 200ms. The page heap size starts at 3.5MB pre-test, and levels out at 3.9MB.
Conclusion
Each timer takes ~.002 msecs to set up, and adds about 35 bytes to the JS heap.
在一个页面上,您可以根据需要同时运行任意多个 setTimeouts/setIntervals,但是为了单独控制每个设置,您需要将它们分配给一个变量。
上面的代码同样适用于setTimeout,只是替换了措辞。
正如 Kevin 所说,JavaScript 确实是单线程的,所以虽然你可以同时有多个计时器计时,但任何时候只有一个可以触发 - 即,如果你有一个触发一个在执行中“停止”的函数,例如一个警报框,那么我相信该 JS 必须“恢复”,然后另一个才能触发。
下面给出另一个例子。虽然标记无效,但它显示了超时的工作原理。
On a page you can have as many setTimeouts/setIntervals running at once as you wish, however in order to control each individually you will need to assign them to a variable.
The same code above applies to setTimeout, simply replacing the wording.
As Kevin has stated, JavaScript is indeed single threaded, so while you can have multiple timers ticking at once, only one can fire at any one time - i.e. if you have one that fires a function which 'halts' in execution, for example with an alert box, then that JS must be 'resumed' before another can trigger I believe.
One further example is given below. While the markup is not valid, it shows how timeouts work.
您可以根据需要使用多个。请记住,JavaScript 是单线程的,因此它们都不能并行执行。
You can use as many as you want. Just remember that JavaScript is single threaded, so none of them can execute in parallel.
var Interval_1 = setInterval("callFunc1();",2000);
调用eval()
这是邪恶的,所以它是坏的。使用这个
var Interval_1 = setInterval(callFunc1,2000);
对于这个问题,你可以使用任意多个,但如果两个操作之间的间隔相同,你最好这样做
var interval_1 = setInterval("callFunc1();",2000);
callseval()
which is evil so it's BAD.Use this instead
var interval_1 = setInterval(callFunc1,2000);
And for the question, you may use as many as you want but if all have the same interval between two actions, you better do it this way