What are Event Loops?
Well, then have a look at this.
If you are not able to guess the output, or having some kind of confusion. Then you are at the right place. The output is -:
Now you should wonder, "why the 500ms code did not run at first?". The answer to this question lies in the Event loops.
Pic Credits- MDN Docs
Whenever a function is called, a frame is formed inside the stack.
Now, let me explain this piece of code step by step.
second is called. Hence the first frame is formed inside the stack.
Step 2: When the
first, another frame is created on top of the first frame.
Step 3: When the
second function logs, the
first function is called and is popped out of the stack.
Step 4: Then the
second function frame is popped out of the stack.
Similar to stack, we also have a queue in the runtime environment.
However, the processing of the function continues until the stack is empty. Then the event loop starts reading messages from the queue. Once the event loop reads the message, the function associated with it is called and the message is handled by that function.
Here, the point to be noted is, first all the functions are executed and the stack is emptied. After that, the execution of messages starts.
Now you must be wondering, what is the difference between a message and a frame? A frame is originated by a function call, while a message is originated when a particular event has happened. For example, '
click'. So I may call a function on a 'click', but that function will be called through a message and not a frame. But the event will only be recorded, whenever their is an
eventlistner attached to it, else the event will be lost.
But the thing to keep in mind is that the event loop reads the next message on the full execution of the previous one.
Suppose a function is given a delay of zero, this doesn't mean that, the callback function will execute immediately, it will depend upon the complete execution of the stack and the messages before the given message.
PROS & CONS
This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be preempted and will run entirely before any other code runs.
But the problem is if some task is taking a long time to execute, for example establishing a connection with a server, or requesting a database, the page will become non-functional, and interaction with the user will be disturbed.
I think this is much for today's article. Try to absorb the knowledge and implement it.
Did you find this article valuable?
Support Saksham Aggarwal by becoming a sponsor. Any amount is appreciated!