What is JavaScript Event Loop ?
JavaScript code runs single threaded. Javascript has a concurrency model based on an event loop. The event loop is in the heart of Node.js / Javascript - it is responsible for scheduling asynchronous operations. 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, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input.
Two main parts of the event loop are the call stack and the message queue.
The call stack is a LIFO queue (Last In, First Out).
The Message Queue is also where user-initiated events like click or keyboard events, or fetch responses are queued before your code has the opportunity to react to them. Or also DOM events like onLoad.
Event Loop is a process that constantly checks whether the call stack is empty, and whenever it’s empty, it checks if the event queue has any functions waiting to be invoked. If it does, then the first function in the queue gets invoked and moved over into the call stack. If the event queue is empty, then this monitoring process just keeps on running indefinitely.
Async callbacks
An asynchronous callback function is just like any other function you’re used to writing in JavaScript, with the added caveat that it doesn’t get executed till later.
The use case of
is to call a function, but execute it once every other function in the code has executed.