You might have heard that Nodejs is single threaded, but how is it able to handle multiple tasks concurrently ?
All thanks to Event loop. Let's try to understand how event loops helps in execution of synchronous and asynchronous code in Nodejs.
It's a loop that is alive till our Nodejs application is up and running. In every iteration of event loop we have to go through 6 different queues, which are:
- Timer Queue: Handles setTimeout and setInterval callbacks.
- I/O Queue: Manages callbacks for I/O operations such as reading files and network requests.
- Check Queue: Executes callbacks from setImmediate.
- Close Queue: Handles cleanup operations.
-
Microtask Queue: Includes two sub-queues:
- Next Tick Queue: Handles process.nextTick callbacks.
- Promise Queue: Handles resolved promises.
So how does the event loop actually works ?
Here is the execution order of event loop
- Executes all synchronous JavaScript code (highest priority).
- Process any pending task within microtask queue, first process.nextTick and then promise queue
- Execute callbacks in the timer queue.
- Check the microtask queue again.
- Execute callbacks in the I/O queue.
- Check the microtask queue again.
- Execute callbacks in the check queue.
- Check the microtask queue again.
- Execute callbacks in the close queue.
- Finally, process any remaining microtasks.
After a complete cycle if any callbacks are still pending, the loops continues for one more iteration following the same path otherwise terminates.
Let's take an example to make it more clear
Here we have 3 console logs:
> console.log('one');
> console.log('two');
> console.log('three');
so what do you think about the output ?
yes, you are right.
> one
> two
> three
Now let again take 3 console logs but let's put the second one inside setTimeout
> console.log('one');
> setTimeout(() => {
> console.log('two');
> }, 0);
> console.log('three');
so now what do you think about the output ?
> one
> three
> two
If you guessed the same congratulations you are right again.
so why this and why not
> one
> two
> three
Even though we have set 0 seconds
as timeout !!
As we mentioned earlier, all synchronous JavaScript code has the highest priority. As the console log
with one & three
are synchronous they are executed first. When the program execution reaches to line 2 it sees setTimeout which is an asynchronous so pushes it to timer queue
and only after all synchronous task are completed the event loops comes into action and it sees that there exists a callback in timer queue
which is a console log
i.e. result of setTimeout
. It print the value two
on console and moves on. If there were other callbacks in other queues, they have to wait until their turn and then be executed. After first iteration as we have no other callbacks left then the event loop exists indicating the end of our program.
So, That's all i know about event loop. If i've missed any points feel free to drop your comments.
Thank you
Top comments (0)