Saturday, June 13, 2015

What is NodeJS Event Loop?

Javascript is single threaded language. NodeJS by extension is single threaded. This means Node application can do exactly one thing at a time. According to that explanation, you can't do parallel executions in node. But javascript have call back functions. This is handled by a concept called event loop by using an event queue.
Write following code in node and check the output.
Now, without waiting two seconds, set it as zero. You may expect result to be in an order of ABC. But check the output.
In javascript, one thread will start the execution of code. When you run that code, in the stack it will put pointer to function A. Then it will run function A. After finished function A, pointer for A in stack will be removed. Then it will add pointer B to stack. Within that function B, there's a time consuming code with a call back. Then javascript will handover to external process. Then callback pointer will be saved in the call back queue. Then Pointer B will be removed from the stack. Then pointer C will added to the stack and function C will execute. Then pointer C will be removed from the stack. Now there aren't anything in the stack. Then, event loop will check stack whether there are anything in the stack. If not, it will check call back queue. If there are, then those call back will push to stack. Then the callback code will run accordingly. Now you will be able to understand about above two programs.

No comments:

Post a Comment