当我在控制台中执行以下代码时,我得到的是:
1,4, undefined 3,2.
I would like to know why its not executing as 1,3,4
and 2
since in setTimeout(function(){console.log(3)}, 0);
the milliseconds param is 0
.
(function() {
console.log(1);
setTimeout(function(){console.log(2)}, 1000);
setTimeout(function(){console.log(3)}, 0);
console.log(4);
})();
原文由 user4483701 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是 John Resig 的一个很好的解释:
http://ejohn.org/blog/how-javascript-timers-work/
But the bottom line is
console.log(1)
and(4)
are executed ‘in-line’ and2
and3
are placed in the event queue,并且在执行所有内联代码之前不要执行。因此,即使延迟是0
对于(3)
,它仍然会在所有语句执行后发生。我在测试您的代码时也没有收到
undefined
消息。