Javascript运行完成工作机制

标签 javascript

我知道 javascript 是单线程的,一次运行一个任务或语句。但是 javascript 的 Run to Completion 特性确实让我感到困惑。我有以下代码:

console.log('1');

setTimeout(function() {

    console.log('2');

    setTimeout(function() {

        console.log('3');

    },0);

},0);

console.log('5');

我预计输出如下:

1
2
3
5

但它给了

1
5
2
3

即使我的所有计时器都为零毫秒,它的表现如何。所以它应该一个接一个地执行,而不需要等待任何东西,因为零毫秒。

谁能给我解释一下这件事。非常感谢。

最佳答案

要理解这一点,您必须熟悉两个 javascript 概念

队列

A JavaScript runtime contains a message queue, which is a list of messages to be processed. A function is associated with each message. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame). The message processing ends when the stack becomes empty again.

将任务添加到队列中

Calling setTimeout will add a message to the queue after the time passed as a second argument. If there is no other message in the queue, the message is processed right away; however, if there are messages, the setTimeout message will have to wait for other messages to be processed. For that reason the second argument indicates a minimum time and not a guaranteed time.

因此,每个同步代码都优先于任何异步代码,这些异步代码会在所有同步完成后被推送到要执行的任务堆栈中

所以你的代码会被这样执行

  1. 记录 1
  2. 将最外层setTimeout(1)的函数压入栈
  3. 日志 5
  4. 完成同步代码
  5. Pop 函数添加到队列 (1) 以供执行
  6. 日志 2
  7. inenr最setTimeout的函数入栈(2)
  8. 完成同步代码
  9. Pop 函数添加到队列 (2) 以供执行
  10. 日志 3

您可以在 MDN article for Event Loop in Javascript 中了解更多信息

注意:您的代码中没有 console.log(4)

注意 2:上面的执行顺序假设您的整个脚本是提供的脚本,并且没有其他超时未显示的代码未决

关于Javascript运行完成工作机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38518826/

相关文章:

javascript - if 语句的多个简写?

javascript - 如何正确加载图片路径?

javascript - Typescript 递归映射对象属性类型 : object and array element types

java - 为什么 Eclipse/JSP 会解析我的 JavaScript?

javascript - 如何在DIV容器中心只显示指定坐标的图片

javascript - Android文件上传 - 文件名错误, native 浏览器

javascript - knockout 自定义处理程序以在禁用时隐藏文本框值

JavaScript Canvas 尺寸

javascript - 如何从 Chrome 远程调试获取 DOM

javascript - 无法在 Firefox 中为同一输入字段触发 ONKEYDOWN 和 ONCHANGE 事件