javascript 立即调用 setTimeout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9083594/
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-10-26 05:33:22  来源:igfitidea点击:

Call setTimeout without delay

javascriptsettimeout

提问by defuz

Quite often see in JavaScript libraries code like this:

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

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

I would like to know why use such a wrapper code.

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

回答by anddoutoi

Very simplified:

非常简化:

Browsers are single threaded and this single thread (The UI thread) is shared between the rendering engine and the js engine.

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

If the thing you want to do takes alot of time (we talking cycles here but still) it could halt (paus) the rendering (flow and paint).

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

In browsers there also exists "The bucket" where all events are first put in wait for the UI thread to be done with whatever it′s doing. As soon as the thread is done it looks in the bucket and picks the task first in line.

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

Using setTimeoutyou create a new task in the bucket after the delay and let the thread deal with it as soon as it′s available for more work.

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

A story:

一个故事:

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 ms 延迟后创建该函数的一个新任务并将其放入存储桶中。在那一刻,UI 线程正忙于做其他事情,而桶中已经有其他任务了。6 毫秒后线程可用并获得你面前的任务,很好,你是下一个。但是什么?那是一件大事!它就像 foreeeeeeever(30 毫秒)!!

最后,现在线程已经完成并来完成你的任务。

Most browsers have a minimum delay that is more then 0 so putting 0 as delay means: Put this task in the basket ASAP. But telling the UA to put it in the bucket ASAP is no guarantee it will execute at that moment. The bucket is like the post office, it could be that there is a long queue of other tasks. Post offices are also single threaded with only one person helping all the task... sorry customers with their tasks. Your task has to get in the line as everyone else.

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

If the browser doesn′t implement its own ticker, it uses the tick cycles of the OS. Older browsers had minimum delays between 10-15ms. HTML5 specifiesthat if delay is less then 4ms the UA should increase it to 4ms. This is said to be consistent across browsers released in 2010 and onward.

如果浏览器没有实现自己的ticker,它会使用操作系统的tick 周期。较旧的浏览器的最小延迟在 10-15 毫秒之间。HTML5规定,如果延迟小于 4 毫秒,UA 应将其增加到 4 毫秒。据说这在 2010 年及以后发布的浏览器中一致的

See How JavaScript Timers Workby John Resig for more detail.

有关更多详细信息,请参阅John Resig 的How JavaScript Timers Work

Edit:Also see What the heck is the event loop anyway?by Philip Roberts from JSConf EU 2014. This is mandatory viewing for all people touching front-end code.

编辑:另请参阅事件循环到底是什么?来自 JSConf EU 2014 的 Philip Roberts。这是所有接触前端代码的人都必须查看的内容。

回答by JaredPar

There are a couple of reasons why you would do this

这样做的原因有几个

  • There is an action you don't want to run immediately but do want to run at some near future time period.
  • You want to allow other previously registered handlers from a setTimeoutor setIntervalto run
  • 有一个操作您不想立即运行,但确实想在不久的将来某个时间段运行。
  • 您希望允许其他先前注册的处理程序从setTimeoutsetInterval运行

回答by Fredrik Blomqvist

Apart from previous answers I'd like to add another useful scenario I can think of: to "escape" from a try-catch block. A setTimeout-delay from within a try-catch block will be executed outside the block and any exception will propagate in the global scope instead.

除了以前的答案,我想添加另一个我能想到的有用场景:从 try-catch 块中“逃脱”。try-catch 块内的 setTimeout-delay 将在该块外执行,并且任何异常都将在全局范围内传播。

Perhaps best example scenario: In today's JavaScript, with the more common use of so called Deferreds/Promises for asynchronous callbacks you are (often) actually running inside a try-catch. Deferreds/Promises wrap the callback in a try-catch to be able to detect and propagate an exception as an error in the async-chain. This is all good for functions that need to be in the chain, but sooner or later you're "done" (i.e fetched all your ajax) and want to run plain non-async code where you Don't want exceptions to be "hidden" anymore. AFAIK Dojo, Kris Kowal's Q, MochiKit and Google Closure lib use try-catch wrapping (Not jQuery though).

也许最好的示例场景:在今天的 JavaScript 中,随着所谓的延迟/承诺用于异步回调的更常见使用,您(通常)实际上是在 try-catch 中运行的。Deferreds/Promises 将回调包装在 try-catch 中,以便能够检测异常并将其作为异步链中的错误传播。这对于需要在链中的函数来说都很好,但是迟早你会“完成”(即获取所有的ajax)并且想要在你不希望异常的地方运行普通的非异步代码“隐藏”了。AFAIK Dojo、Kris Kowal 的 Q、MochiKit 和 Google Closure lib 使用 try-catch 包装(虽然不是 jQuery)。

(On couple of odd occasions I've also used the technique to restart singleton-style code without causing recursion. I.e doing a teardown-restart in same loop).

(在一些奇怪的情况下,我还使用了该技术来重新启动单例样式代码而不会导致递归。即在同一循环中执行拆卸重新启动)。

回答by Senad Me?kin

When you want to execute rest of your code without waiting previous one to finish you need to add it in anonymous method passed to setTimeout function. Otherwise your code will wait until previous is done

当您想在不等待前一个代码完成的情况下执行其余代码时,您需要将其添加到传递给 setTimeout 函数的匿名方法中。否则您的代码将等到上一个完成

Example:

例子:

function callMe()
{
   for(var i = 0; i < 100000; i++)
     {
       document.title = i;
     }
} 

var x = 10;
setTimeout(callMe, 0);

var el = document.getElementById('test-id');
el.innerHTML = 'Im done before callMe method';

That is the reason I use it.

这就是我使用它的原因。

回答by HBP

To allow any previously set timeouts to execute.

允许执行任何先前设置的超时。