Home / Event Loop? π π΅
JavaScript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.
Single-Threaded means that JS can only run one instruction at a time, even if your CPU has multiple cores and available threads.
Some Runtime Concepts:
β‘ Stack π
β‘ Heap βοΈ
β‘ Queue π
Event Loop is essentially an infinite loop which keeps on checking if something exists in the queue. Its most basic implementation can be imagined as:
while (queue.waitForMessage()) {
queue.processNextMessage();
}
Here is an example to understand better:
const first = () => console.log("First");
const second = () => setTimeout(() => console.log("Second"), 1000);
const third = () => console.log("Third");
first();
second();
third();
// Output
// JavaScript will first run the synchronous code then it will look for messages in the queue.
First;
Third;
Second;
See the above code here
Now, if we set the setTimeout with a delay of 0
(zero) milliseconds doesnβt execute the callback function after the given interval.
const second = () => setTimeout(() => console.log("Second"), 0);
The output will remain the same! π€―
A 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, so when the application is waiting for a database query to return or an XHR/API request to return, it can still process other things like user input.
Lets recapitulate π:
For each round of Event Loop JavaScript will:
β‘ Run synchronous code.
β‘ Run [Promise](/javascript-notes/notes/promises.html) or microtask callbacks.
β‘ Run asynchronous code.
See Also:
β« Promises π€ and Async/Await π€― Read βΆ
β« Datatypes in JavaScript. π Read βΆ