简体   繁体   中英

Node.js Event Loop and Call stack

I have a piece of code that uses the setTimeout method as such

setTimeout(() => {
 console.log('Hello');
},1000);

For the duration of the 100ms or 1s where is the setTimeout method? Has it been passed to the system kernel until the callback is ready to be executed or has the V8 passed it to another Queue?

() => {
 console.log('Hello');
}

This is the function that is executed after the timeout interval.

Based on the setTimeout method you have written, it waits for a minimum of 1000ms, then executes the console.log method after the all current tasks are executed as it is placed at the back of the queue

It is queued on libuv. V8 engine has own execution stack. When times up and main thread is available, v8 engine's next execution stack will be

    () => {
     console.log('Hello');
    }

Source code for node's Timers is here and here .

setTimeout will create a new Timeout object which will get appended to a linkedlist itself added to a timerListMap object, which is just a plain JS Object where keys represent the duration in ms and values are the linkedlists .
Finally, this timerListMap object is queued in the timerListQueue PriorityQueue which once again is just a JS class instance.

Then when the event loop (libuv) will call processTimers(now) with a now value larger than the passed timeout, the callback will get retrieved following the reverse route.

So this all means that, in node , the callbacks to timeouts stay in the JS heap the whole time, the whole Timers logic stays in the JavaScript layer and only the asynchronous peeking is initialized by libuv event loop.

See the specification for the "timer initialization steps":

  1. If method context is a Window object, wait until the Document associated with method context has been fully active for a further timeout milliseconds (not necessarily consecutively).

After this finishes, the function gets executed; the task for the function only gets queued after this point. Before this point, it only exists inside the browser's internal (implementation-dependent) timer code.

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