while(true)vs setInterval(function(),0) [英] while(true) vs setInterval(function(),0)
问题描述
$ b
调用函数或重复执行代码片断,每次调用该函数之间的固定时间延迟。
while()
只要测试条件的计算结果为true,就创建一个执行指定语句的循环。如果我使用
while (true)
来执行特定语句,我的浏览器崩溃( Firefox ),滞后( Opera ),或者语句不会( Chrome )执行,但如果我使用固定时间 0秒的setInterval()
,则一切正常,即使它只有0秒,而while(true)
在逻辑上不能超过0秒,但为什么会发生这种情况?
while()示例:
<!DOCTYPE html>
< html>
< body>
< div id =counter>< / div>
< script>
var i = 0;
while(true)
{
document.getElementById(counter)。innerHTML + = i ++;
}
< / script>
< / body>
< / html>
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>
解决方案第一种方法,
while
循环将会锁定用户的cpu,因为它永远运行而不会停止,并占用处理器的100%。setInterval
实际上具有隐含的最小数量,并且取决于浏览器。我相信它大约是10毫秒。所以,你的setInterval
实际上只运行一毫秒左右,每10ms进行一次简单的更新。这对处理器来说很苛刻,但不需要100%的处理器,并且可以通过操作系统的任务管理来缓解。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 usedsetInterval()
with a fixed time of 0 seconds, everything works perfectly, even though its only 0 seconds, andwhile(true)
can't logically be faster than 0 seconds, but why does this happen?while() example:
<!DOCTYPE html> <html> <body> <div id="counter"></div> <script> var i = 0; while (true) { document.getElementById("counter").innerHTML += i++; } </script> </body> </html>
setInterval() example:
<!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>
解决方案There is a large difference which involves locking. The first approach, the
while
loop is going to lock up the user's cpu because it runs forever without stopping and will take up 100% of the processor.setInterval
actually has a minimum amount which is implicit, and depends on the browser. I believe it is around 10ms. So, yoursetInterval
is 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(true)vs setInterval(function(),0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!