(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之前?
“块”完成后,超时被推到处理堆栈的底部。所以这就是引擎看到它的方式:
Log 1
Set a timeout 1s later to log 2
Set a timeout 0s later to log 3
Log 4
Run all timeouts
因为当前函数的执行将在任何超时运行之前完成。
setTimeout(function(){console.log(3)}, 0);
添加超时功能但当前功能在其中任何一个将触发之前完成。