setTimeout(函数(){console.log(3)}, 0);它的值为 0

新手上路,请多包涵

当我在控制台中执行以下代码时,我得到的是:

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 许可协议

阅读 183
1 个回答

这是 John Resig 的一个很好的解释:

http://ejohn.org/blog/how-javascript-timers-work/

But the bottom line is console.log(1) and (4) are executed ‘in-line’ and 2 and 3 are placed in the event queue,并且在执行所有内联代码之前不要执行。因此,即使延迟是 0 对于 (3) ,它仍然会在所有语句执行后发生。

我在测试您的代码时也没有收到 undefined 消息。

原文由 nril 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题