JavaScript - When exactly does the call stack become “empty”?

流过昼夜 提交于 2019-12-02 22:45:20

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.

jfriend00

When the current piece of Javascript that is executing has finished and has no more sequential instructions to execute, then and only then will the JS engine pull the next item out of the event queue.

So, in your example:

f();
b();
// JS is done executing here so this is where the next item will be
// pulled from the event queue to execute it

Javascript is single-threaded which means the current thread of Javascript runs to completion, executing all instructions within a sequence until it hits the end of the code. Then, and only then, does it pull the next item from the event queue.

Here are some other answers that may help you understand:

How Javascript Timers Work

How does JavaScript handle AJAX responses in the background? (a whole bunch of Event Loop references in this post)

Do I need to be concerned with race conditions with asynchronous Javascript?

Can JS event handlers interrupt execution of another handler?

The best way I can think to explain it is that the call stack isn't empty until the code finishes running all relevant paths. A setTimeout of 0 simply pushes your code to the end of the stack.

When code runs at runtime, everything that will be run is part of the call stack, the order will be adjusted based on the order things are called and any timeouts/intervals/async methods that are called.

Some examples:

function foo() {
  console.log('foo');
}

function bar() {
  baz();
  console.log('bar');
}

function baz() {
  setTimeout(function() { console.log('timeout') }, 0);
  console.log('baz');
}

foo();
baz();
// call stack ends here, so, timeout is logged last.

// in console
// foo
// baz
// timeout

As you can see, bar is not included in the runtime stack because it is not called. If we have some HTML:

<div onclick="bar()">Bar runs</div>

When you click on that div, you will see baz, bar, then timeout logged to the console because the timeout is always pushed to the end of the currently running processes/call stack.

Hope this explanation helps!

The simplest possible explanation: when all synchronous code in the current script, function, or event handler has finished running.

To directly answer "what if I have millions of lines..." Yes - your setTimeout call is stuck in the queue and will wait for its turn.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!