为什么setTimeout(..,0)不立即执行?

Paw*_*weł 5 javascript settimeout

var timeout = setTimeout(function(){
     console.log("I'm message from timeout");
},0);

console.log("I'm message from outside timeout");

//1. I'm message from outside timeout
//2. I'm message from timeout
Run Code Online (Sandbox Code Playgroud)

尽管将setTimeout时间设置为0,为什么内部指令不会先执行?我使用各种时间,包括0/null,我想知道如何保留setTimeout对象并使用流程执行其指令.

brk*_*brk 6

Javascript代码仅在一个线程上运行.setTimeout安排一个稍后运行的功能.所以在js中当所有当前运行的代码完成其执行时,event循环将查找任何其他事件.因此,setTimeout( .. 0)将使代码在当前循环之后运行.

console.log("I'm message from outside timeout");将首先安排执行.一旦完成,setTimeout将执行

所以底线setTimeout(myfunction ,0)将在当前执行函数后运行myms 0ms.在你的情况下,当前的执行循环是

console.log("I'm message from outside timeout");
Run Code Online (Sandbox Code Playgroud)

如果你添加另一个console.log("我是来自timeout1外部的消息"); 所以当前事件循环将首先记录

I'm message from outside timeout
I'm message from outside timeout1
Run Code Online (Sandbox Code Playgroud)

在开始setTimeout功能之前 .

注意 setTimeout最小超时为4毫秒.您可以查看此Stackoverflow线程以了解有关它的更多信息

  • 关于"*...最小超时4ms*",这不一定是真的.当前[*WHATWG规范*](https://html.spec.whatwg.org/multipage/webappapis.html#timers)说"*...在五个这样的嵌套计时器之后,但是,间隔被强制至少为四个毫秒*".因此,最小延迟是它设置的实现. (4认同)
  • 你解释订单的方式令人困惑.`setTimeout`本身在`console.log`之前执行,只有函数传递*to*它被调度. (2认同)