"JavaScript is asynchronous and single-threaded"
How?
Heap
Objects are allocated in a heap (large mostly unstructured regions of memory)
Stack
Represents the single thread provided for JavaScript code execution. Function calls are stacked
Browser or Web APIs
- Built into the browser
- Expose data from the browser
- Not part of the JavaScript language itself, built on top of it
Example
```js
function main() {
console.log('A');
setTimeout(function exec() {
console.log('B');
}, 0);
console.log('C');
}
main();
```
```js
A
C
B
```
1 - console.log('A')
- Call to main() -> stack
main()
's first statement -> stack
- A is displayed in the console
2 - setTimeout
setTimeout
(with callback exec() and 0ms) -> stack
- Execution starts
setTimeout
function uses a Browser API to delay a callback to the provided function
setTimeout
is popped out once the handover to browser is complete (for the timer of 0ms)
3 - console.log(āCā)
console.log(āCā)
-> stack
- Meanwhile, the timer runs in the browser for the callback to the
exec()
function
- Here with 0ms, the callback will be added to the message queue as soon as the browser receives it
4 - Message queue
console.log('C')
popped out
main()
popped out
- call stack empty
- Browser can push messages from the queue to call stack
5 - exec
exec()
callback -> call stack
- exec executed
- B is displayed in the console
Conclusion
- In
setTimeout(function, delayTime)
, delayTime != delay after which the function is executed
- It is the minimum wait time after which at some point the function will be executed
More (from Node doc)
More (from Node doc)
- timers: this phase executes callbacks scheduled by setTimeout() and setInterval()
- pending callbacks: executes I/O callbacks deferred to the next loop iteration
- idle, prepare: only used internally
More (from Node doc)
- poll: retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate());- node will block here when appropriate
- check: setImmediate() callbacks are invoked here
- close callbacks: some close callbacks, e.g. socket.on('close', ...)