Event Loop
JavaScript has a concurrency model based on an "event loop". The event loop got its name because of how it's usually implemented, which usually resembles:
while (queue.waitForMessage()) {
queue.processNextMessage();
}
queue.waitForMessage()
waits synchronously for a message to arrive if there is none currently.
- Each message is processed completely before any other message is processed.
setTimeout
message: a minimum time and not a guaranteed time.- A web worker or a cross-origin
iframe
has its own stack, heap, and message queue. - A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks
Node JS Architecture – Single Threaded Event Loop
- The first basic thesis of node.js is that I/O is expensive.
- The second basic thesis is that thread-per-connection is memory-expensive.
- There is no way of making code run in parallel within a single request. However, all I/O is evented and asynchronous.