gpt4 book ai didi

javascript - 我不太了解 javascript 中的 setTimeout 和线程

转载 作者:行者123 更新时间:2023-11-28 02:10:54 25 4
gpt4 key购买 nike

我在Events and timing in-depth中找到了一篇文章,这篇文章中有一个例子:

function run() {
var div = document.getElementsByTagName('div')[0]
for(var i=0xA00000;i<0xFFFFFF;i++) {
div.style.backgroundColor = '#'+i.toString(16)
}
}

上面写着:

In most browsers, you see nothing until the script finishes, or until the browser pauses it with a message that ‘a script is running too long’.

这意味着在执行这些代码时我看不到动画。

但是为什么?我不太明白,是代码执行太快了吗?或者执行代码后渲染工作就完成了?

为什么添加setTimeout可以显示动画?

最佳答案

run()函数执行时,浏览器不会更新页面。它会等待直到该函数完成执行。但是,使用 setTimeout 时,它会以增量方式运行 - 浏览器会在每次运行时/之后更新页面。

您问题中链接的摘要很好地解释了这一点:

Most browsers use single thread for UI and JavaScript, which is blocked by synchronous calls. So, JavaScript execution blocks the rendering.

Events are processed asynchronously with the exception of DOM events.

The setTimeout(..,0) trick is very useful. It allows to:

Let the browser render current changes. Evade the “script is running too long” warning. Change the execution flow. Opera is special in many places when it comes to timeouts and threading.

关于javascript - 我不太了解 javascript 中的 setTimeout 和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17106101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com