JavaScript - 调用堆栈什么时候变成“空”? [英] JavaScript - When exactly does the call stack become "empty"?

查看:316
本文介绍了JavaScript - 调用堆栈什么时候变成“空”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在事件循环中阅读了几个帖子/ SO线程,并根据 MDN的文章

I've read several posts/SO threads on event loop, and according to MDN's article,


当堆栈为空时,邮件从队列中取出,

When the stack is empty, a message is taken out of the queue and processed.

作为一个JS新手,我仍然困惑的是 - 当调用堆栈变成空 ?例如,

As a JS novice, what I'm still confused about is -- when exactly does the call stack become "empty"? For example,

<script>
function f() {
  console.log("foo");
  setTimeout(g, 0);
  console.log("foo again");
}
function g() {
  console.log("bar");
}
function b() {
  console.log("bye");
}

f();
/*<---- Is the stack empty here? */
b();
</script>

执行的正确顺序是 foo foo again - bye - bar

The correct order of execution is foo - foo again - bye - bar.

但是今天我开始想:在退出 f()调用之后,堆栈技术上是不是空的?我的意思是,我们不在任何函数内,并且我们没有开始任何新的执行,所以不应该 setTimeout 调用消息(它已经立即排队),然后移动到 b(),并给出 foo - foo again - - bar - bye

But today I started thinking: isn't the stack technically empty right after exiting the f() call? I mean at that point we're not inside any function, and we haven't started any new execution, so shouldn't the setTimeout call message (which has been immediately queued) be processed, before moving on to b(), and giving the order of foo - foo again - bar - bye?

如果我们有万行代码或一些密集计算来执行,并且 setTimeout(func,0)只是在队列中长久?

What if we have a million lines of code or some intensive computation to be executed and the setTimeout(func, 0) just sits in the queue for however long?

推荐答案

虽然< script> 标记中的代码块不包含在显式函数中,它可以是有用的,认为它是一个全局函数,浏览器告诉JavaScript运行时执行。因此调用堆栈不是空的,直到脚本块中的代码执行完毕。

Although the block of code within the <script> tags isn't wrapped in an explicit function, it can be helpful to think of it as being a global function that the browser tells the javascript runtime to execute. So the call stack isn't empty until the code in the script block is done executing.

这篇关于JavaScript - 调用堆栈什么时候变成“空”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆