Dale- / Web-Alpha-To-Omega

from α to Ω build web page
5 stars 0 forks source link

setTimeout(fn, 0) #4

Open Dale- opened 6 years ago

Dale- commented 6 years ago
setTimeout(function(){
    console.log(1);
}, 0);
console.log(2);
console.log(3);

这样,这段代码的输出结果为2,3,1就得到了解释,因为setTimeOut设置为0,会在队列最后添加一个事件,要等待其他任务事件处理完成才会处理,最后1才会打印。

Dale- commented 6 years ago
console.log(1);

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

Promise.resolve().then(function() {
  console.log(3);
}).then(function() {
  console.log(4);
});

console.log(5);

执行结果 1 5 3 4 2