Who is the target audience of this post?
The stack of frames
For better visualization, we will start with the code example:
When calling the calculate function, the first frame is pushed to the stack. After that, the add function is called and the second frame is pushed on the top of the stack. The same goes for multiply function. We can say that each frame represents a function. The stack is full, and when multiply function returns a value, the first element on top of the stack popped out of the stack, in this case, multiply function. After that add function is executed and popped out of the stack, leaving only calculate function in the stack and when the last line in the calculate function is executed, calculate function popped out of the stack and stack is now empty. We should see a result in the browser console. It's that simple.
Every time you use a function to make an AJAX request or manipulate DOM with events like onClick or onEnter, that function gets pushed to the message queue where it waits to be executed, and this is where event loop comes in.
The event loop is an infinite loop which checks if the stack is empty, and if it is, it pushes first thing from the message queue to the stack. All event loop does is wait for a message (function) in the message queue. Here is the example of event loop implementation:
Visualize this with code examples for better understanding.
First, let's see what would happen if we do not have the message queue and event loop:
In this example, we make two requests and we'll say that each request takes ten. That means that the user is going to wait for twenty seconds to make the next step on a web page and that’s not good UX. If one of these requests does not end, the user could stay forever on a web page.
The setTimeout function accepts three parameters: the first one is callback function which should be executed; the second parameter is the number of milliseconds to wait before running the code, and the third parameter is additional parameters for the function. But third parameters are not important for us now. The first parameter is required, and other parameters are optional. If you omit the second parameter, the value 0 is used. Here is the result of this code example.
Note about setTimout function and the second parameter: the second parameter is the minimum time to execute. It does not represent the time after which the function will be executed.