gpt4 book ai didi

javascript - 立即调用 setTimeout

转载 作者:IT王子 更新时间:2023-10-29 03:11:04 24 4
gpt4 key购买 nike

在 JavaScript 库中经常看到这样的代码:

setTimeout(function() {
...
}, 0);

我想知道为什么要使用这样的包装代码。

最佳答案

非常简单:

浏览器是单线程的,这个单线程(UI 线程)在渲染引擎和 js 引擎之间共享。

如果你想做的事情需要很多时间(我们在这里谈论周期但仍然)它可能会停止(暂停)渲染(流动和绘画)。

在浏览器中也存在“桶”,其中所有事件首先被放入等待 UI 线程完成它所做的任何事情。一旦线程完成,它就会在桶中查找并首先选择队列中的任务。

使用 setTimeout,您可以在延迟后在桶中创建一个新任务,并让线程在它可用于更多工作时立即处理它。

一个故事:

After 0 ms delay create a new task of the function and put it in the bucket. At that exact moment the UI thread is busy doing something else, and there is another tasks in the bucket already. After 6ms the thread is available and gets the task infront of yours, good, you´re next. But what? That was one huge thing! It has been like foreeeeeever (30ms)!!

At last, now the thread is done with that and comes and gets your task.

大多数浏览器都有一个大于 0 的最小延迟,所以将 0 作为延迟意味着:尽快将此任务放入篮子中。但是告诉 UA 尽快将其放入桶中并不能保证它会在那一刻执行。桶就像邮局,可能是其他任务排得很长。邮局也是单线程的,只有一个人帮助完成所有任务……对不起客户的任务。你的任务必须和其他人一样排队。

如果浏览器没有实现自己的代码,它会使用操作系统的代码周期。旧版浏览器的最小延迟在 10-15 毫秒之间。 HTML5 specifies如果延迟小于 4ms,UA 应该将其增加到 4ms。这据说是consistent across browsers released in 2010 and onward .

参见 How JavaScript Timers Work由 John Resig 提供更多详细信息。

编辑:另见 What the heck is the event loop anyway?作者:来自 JSConf EU 2014 的 Philip Roberts。这是所有接触前端代码的人必看的内容。

关于javascript - 立即调用 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9083594/

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