Non-Blocking event loop in Node.js
NodeJS has the ability to do multiple things at the same time is called asynchronous programming.
Think of a waiter working in a restaurant. He goes around the restaurant taking orders from customers and serving them when their respective food is ready. What happens when the waiter takes an order from a customer and waits until the food is prepared, serves it and then proceeds to the next customer. This way the waiting time for each customer increases and the restaurant would be a huge flop. The latter represents synchronous programming and the earlier one represents asynchronous programming.
Example: Have a look at the below code-snippet for getting a better understanding of the non-blocking nature of Node.js.
As you can see, the rest of the program is unaffected by the long delay. But why did “I should wait for 0 seconds before execution” print after “It’s time for me to end”. Well, let’s get deeper into the internal working of Node.js.
The Call Stack :Any Node.js function, when invoked, goes into the call stack. The first function to be invoked is the main function. When a function is done performing it’s job, it gets removed from the call stack.
The CallBack Queue :The Callback queue holds the asynchronous functions which are ready to be executed (i.e the long waiting period is done). The items present in the callback queue are only called, when the call stack becomes empty.
The Event Loop :Once the Call Stack is empty, the event loop keeps checking the CallBack Queue for executing the asynchronous functions.
How the code is executed:
Step 1: The main function is pushed to the call stack.
Step 2: The first console.log statement is pushed to the call stack.
Step 3: “First one to start” is printed and the console.log function is removed from the call stack.
Step 4: The setTimeOut(3000) function is given to the browser for processing.
Step 5: The setTimeOut(0) function is given to the browser for processing.
Step 6: The setTimeOut(0) function has been processed and given to the CallBack Queue.
Step 7: The last console.log statement is pushed to the call stack.
Step 8: “It’s time for me to end” is printed and the console.log function is removed from the call stack.
Step 9: The main function is removed from the call stack and the event loop starts running.
Step 10: The console.log function present in setTimeOut(0) is pushed to the call stack.
Step 11: “I should wait for 0 seconds before execution” is printed and the console.log function is removed from the call stack.
Step 12: After waiting for 3 seconds, the browser gives the setTimeOut(3000) function to the CallBack Queue.
Step 13: The console.log function present in setTimeOut(3000) is pushed to the call stack.
Step 14: “I should wait for 3 seconds before execution” is printed and the console.log function is removed from the call stack.