简体   繁体   中英

Why is the call stack not empty before executing the function in Task Queue?

function first() {
    function second() {
        setTimeout(function () {
            console.log('hello') /*break point here on chrome dev*/
        }, 1000);
    }
    second()
}
first();

Per my understanding of Event Loop:

  1. Look at the call stack and task queue
  2. If the call stack is empty then take the first thing on the task queue and push on the call stack and the stack runs it.

My question is: why the call stack is:

------------------
(anonymous)
setTimeout (async)
-----------------
second
-----------------
first
-----------------
(anonymous)
-----------------

instead of:

-----------------
(anonymous) [callback Fn passed in setTimeout] 
-----------------

Based on the Event Loop (see #2 definition), the first and second execution context should have been already popped up off the call stack before executing the callback function in setTimeout.

You see this trace because your dev-tools are configured to keep the async calls trace.

See this doc for few details.

You can disable this by typing Do not capture async stack trace in the "Run command" menu ( CTRL + SHIFT + P from your dev-tools).

The real stack is indeed empty before the event loop picks the next async task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM