So basically, the event loop is something that is continuously running in the background of your website only if there is nothing in the call stack. It does 3 things:
- Invokes functions sitting in the call stack.
- Checks the event table for functions.
- Checks the message queue for functions.
The call stack contains functions that need to be invoked. If the functions have any callbacks, those will get added into the event table to be invoked when it is time to do so.
Example: Let’s say the current time is 2:00:00pm, and the call stack contains this function that logs “Hello World” after 1 second.
setTimeout(console.log("Hello World"), 1000);
That will get invoked, and the callback function console.log(“Hello World”) would be added to the event table with the time set to 2:00:01pm.
The event table stores more functions with the specific time that they should be ran. If the time in the table is greater or equal to the current time, then the function will be moved to the message queue.
Example: console.log(“Hello World”) would only be added to the message queue when the clock has turned to 2:00:01pm.
Lastly, the message queue contains functions that are next in line to be ran. These functions will be popped off the queue and be added to the call stack.
Example: console.log(“Hello World”) will be moved into the call stack. This completes a full circle, and the event loop will repeat again.