I was trying to understand what’s an event loop in JavaScript. Came across Mozilla Developer Network’s link about event loop.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop
It mentions
Queue
A JavaScript runtime contains a message queue, which is a list of messages to be processed. To each message is associated a function. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame). The message processing ends when the stack becomes empty again.
What does it mean message queue in this context? Is it referring to every click or keyboard event we perform in browser? Each of this event is a message and added to queue?
Please clarify.
Advertisement
Answer
The term “message queue” means pretty much what it sounds like. It’s a queue of messages to process (read: event callbacks to execute), one at a time and in order.
This “message queue” is not part of ECMAScript, but is rather used to describe the behavior of processing asynchronous events in a single-threaded execution model – every browser event (clicks, timers, AJAX, etc) is added to the queue and processed in the same manner. Similarly, node.js uses events for asynchronous I/O operations.
The “message queue” is processed until is empty (by the “event loop”) whenever there is no JavaScript executing for the given global context (i.e. window or process). This is why blocking JavaScript is bad – it will prevent the queue from being processed (which prevents event callbacks from being performed) until the blocking code stops executing.
The event queue / event loop in node.js works the same way as a browser, just with different events. This is how node.js can support concurrency without exposing multiple threads and the associated complexity.
One of the most common ways fro code to add messages to this “message queue” is with setTimeout
– the callback is added to the queue when the timeout expires. Assuming a little white-lie (as the callbacks are only added to the queue when the event actually occurs), consider that
setTimeout(f, 0) setTimeout(g, 0)
will “queue” the callbacks in the sequence f, g
while
setTimeout(f, 20) // MUST exceed time to g event firing setTimeout(g, 0)
will “queue” the callback sequence g, f
. These sequence guarantees can be relied upon because (of the setTimeout guarantees and that) the messages/events added to the queue are processed in order.
Since the code above is running (e.g. JavaScript is being executed) it is also guaranteed that neither the f
nor the g
callbacks will be invoked before the given JavaScript stops executing and the “message queue” can be processed. However, there is no general guarantee that (in either case) an additional event/callback is not processed between f
and g
.