Javascript while(true) vs setInterval(function(),0)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14840527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:06:30  来源:igfitidea点击:

while(true) vs setInterval(function(),0)

javascripthtml

提问by Ali Bassam

setInterval()

设置间隔()

Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.

重复调用函数或执行代码片段,每次调用该函数之间有固定的时间延迟。

while()

尽管()

Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.

创建一个循环,只要测试条件评估为真,就执行指定的语句。在执行语句之前评估条件。

If I use while(true)to execute a specific statement, my browser either crashes(Firefox), lags(Opera), or the statement won't be executed(Chrome), but if I used setInterval()with a fixed time of 0 seconds, everything works perfectly, even though its only 0 seconds, and while(true)can't logically be faster than 0 seconds, but why does this happen?

如果我while(true)用来执行特定的语句,我的浏览器要么崩溃(Firefox),滞后(Opera),要么语句不会被执行(Chrome),但如果我使用0 秒setInterval()的固定时间,一切正常,即使它只有 0 秒,并且在逻辑上不能快于 0 秒,但为什么会发生这种情况?while(true)

while()example:

while()示例:

<!DOCTYPE html>
<html>
    <body>
        <div id="counter"></div>
        <script>
            var i = 0;
            while (true)
            {
                document.getElementById("counter").innerHTML += i++; 
            }
        </script>
    </body>
</html>

setInterval()example:

setInterval()示例:

<!DOCTYPE html>
<html>
    <body>
        <div id="counter"></div>
        <script>
            var i = 0;
            setInterval(function() { counter() }, 0);
            function counter()
            {
               document.getElementById("counter").innerHTML += i++;
            }
        </script>
    </body>
</html>

采纳答案by Travis J

There is a large difference which involves locking. The first approach, the whileloop is going to lock up the user's cpu because it runs forever without stopping and will take up 100% of the processor. setIntervalactually has a minimum amount which is implicit, and depends on the browser. I believe it is around 10ms. So, your setIntervalis actually only running for a millisecond or so doing that simple update, once every 10ms. This is harsh on the processor, but will not require 100% of the processor and can be mitigated with task management by the operating system.

有很大的不同,涉及锁定。第一种方法,while循环将锁定用户的 cpu,因为它永远运行而不会停止,并且会占用 100% 的处理器。setInterval实际上有一个隐含的最小值,取决于浏览器。我相信大约是 10 毫秒。因此,您setInterval实际上只运行一毫秒左右,每 10 毫秒执行一次简单的更新。这对处理器来说很苛刻,但不需要 100% 的处理器,并且可以通过操作系统的任务管理来缓解。

回答by David McMullin

Javascript in browsers is single threadedand event driven. No two things run concurrently, ever, and the event loop is king. If your JS never gives up control of the single thread (by ending a function), then nothing else can use the thread. The same thread handles JS and DOM, so the user can't even scroll or click on anything if your JS is hogging the thread.

浏览器中的 Javascript 是单线程事件驱动的。永远不会有两件事同时运行,事件循环才是王道。如果你的 JS 永远不会放弃对单线程的控制(通过结束一个函数),那么没有其他东西可以使用该线程。同一个线程处理 JS 和 DOM,因此如果您的 JS 占用线程,用户甚至无法滚动或单击任何内容。

setInterval(or indeed setTimeout) with a delay of 0 (milliseconds, not seconds) only means add this function to the event queue after the given delay, there is no guarantee the function will be executed at that exact time.

setInterval(或确实setTimeout)延迟为 0(毫秒,而不是秒)仅意味着在给定延迟后将此函数添加到事件队列中,无法保证该函数将在该确切时间执行。

EDIT : actually, web workers can run JS at the same time as the main browser thread, but they don't see any of the same memory / can't access the DOM, so the points / assumptions above still hold, sort of... If you want to get into Web workers, you'll want a pretty good understanding of JS / functional programming.

编辑:实际上,网络工作者可以在浏览器主线程的同时运行 JS,但是他们看不到任何相同的内存/无法访问 DOM,所以上面的点/假设仍然成立,有点。 .. 如果你想进入 Web 工作者,你需要对 JS / 函数式编程有很好的理解。

EDIT (again) : Why do you want to loop forever? If you are polling (only reason I could think of), please don't do that. There's almost always a better way, especially in JS. The functional way, is to define the function you want executed when an event occurs (the thing you were polling for), and then attach that function to the event (how you do this depends on the event).

编辑(再次):你为什么要永远循环?如果您正在投票(我能想到的唯一原因),请不要这样做。几乎总是有更好的方法,尤其是在 JS 中。函数式方法是定义事件发生时要执行的函数(您正在轮询的对象),然后将该函数附加到事件(如何执行此操作取决于事件)。

回答by fresskoma

  • while(1)generates an infinite loop, that is, JavaScript will simply run forever and nevergive control back to the browser, which therefor freezes, because it is unable to to anything else ever again (until the script is killed).

  • setTimeout(func, 0)behaves differently in the sense that after it executes, control is given back to the browser, which may then decide what to do after. Setting 0ms in setTimeoutdoes not guaranteethat the JavaScript code is run directly after it stops. With the 0ms parameter you merely tell the browser that you'd like the code to run directly after it stops, but the browser is free to do something else entirely before actually doing so.

  • while(1)生成一个无限循环,也就是说,JavaScript 将永远运行并且永远不会将控制权交还给浏览器,浏览器因此冻结,因为它无法再执行任何其他操作(直到脚本被终止)。

  • setTimeout(func, 0)在执行之后,控制权交还给浏览器,浏览器可能会决定之后做什么。设置 0ms insetTimeout并不能保证JavaScript 代码在停止后直接运行。使用 0ms 参数,您只需告诉浏览器您希望代码在停止后直接运行,但浏览器可以在实际执行之前完全自由地执行其他操作。

回答by Adrian Salazar

while(true) will block any execution until the conditional loop is finished, which we already know will never happen. (Chrome)

while(true) 将阻止任何执行,直到条件循环完成,我们已经知道这永远不会发生。(铬合金)

setInterval tells the environment to execute arbitrary code every x milliseconds, it wont block your browser because the "scheduler" has still the control.

setInterval 告诉环境每 x 毫秒执行一次任意代码,它不会阻止您的浏览器,因为“调度程序”仍然拥有控制权。

回答by Ketchup God

Do you have a particular reason for using a never-ending loop, and even, manipulating the DOM with every each step?

您是否有特别的理由使用永无止境的循环,甚至在每一步操作 DOM?

If you use the whileloop it'll most likely to lock the browser and client completely, also causing a possible CPU over-load if not terminated in a way.

如果您使用while循环,它很可能会完全锁定浏览器和客户端,如果没有以某种方式终止,也会导致可能的 CPU 过载。

The loop whiletries to finish it's work in the most possible least microseconds. So it may even try to execute a million steps in a possible second, and maybe even more, in this case it depends on the client. However, at such speed updating the DOM wouldn't be possible.

循环while试图在尽可能少的微秒内完成它的工作。因此,它甚至可能会尝试在可能的秒内执行一百万步,甚至可能更多,在这种情况下,它取决于客户端。然而,以这样的速度更新 DOM 是不可能的。

In the case for setInterval, it's quite different from whileloop, in fact, it's more appropriate to call it a function repeater. It repeats the given function after the given time is passed. So even if the time is 0, it has a step where it checks if the waiting time has passed now, and should the next repeat be run.

在 for 的情况下setInterval,它与whileloop 有很大不同,实际上,将其称为 a 更合适function repeater。它在给定的时间过后重复给定的功能。因此,即使时间为 0,它也有一个检查 的步骤if the waiting time has passed now, and should the next repeat be run

So you may consider while loop more instant than of 0 seconds delay.

因此,您可以考虑 while 循环比 0 秒延迟更即时。