为什么这个序列是真的?

问题描述 投票:4回答:2
(function() { console.log (1);
  setTimeout(function(){console.log(2)}, 1000);
  setTimeout(function(){console.log(3)}, 0); 
  console.log(4); 
})();

输出为:1 4 3 2

为什么3之前没有3,因为超时是0ms,不应该立即执行,因此在4之前?

javascript
2个回答
1
投票

“块”完成后,超时被推到处理堆栈的底部。所以这就是引擎看到它的方式:

Log 1
Set a timeout 1s later to log 2
Set a timeout 0s later to log 3
Log 4
Run all timeouts

1
投票

因为当前函数的执行将在任何超时运行之前完成。

setTimeout(function(){console.log(3)}, 0);

添加超时功能但当前功能在其中任何一个将触发之前完成。

© www.soinside.com 2019 - 2024. All rights reserved.