I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.
#9. Callback Queue and Event Loop
setTimeout(() => console.log(‘hello’), 0);console.log(‘world’);
If you execute this code, the result will be like below.
If you didn’t predict the result, this post might be helpful to you.
WEB APIs are everything related to the DOM, Timers like SetTimeout, Fetch API and even the console.log that we use all the time.
This is the data structure that contains all the callback functions that are ready to be executed
With this basic knowledge, let’t go back to our first code example.
As soon as the code is executed,
console.log(‘world’) is placed in the callstack. However
console.log(‘hello’) is placed in the WEB APIs since
setTimout is a function that WEB APIs support. And then, because i set the timer to 0 second, it is immediately moved to callback queue
Note that the 0 millisecond (second argument of
setTimeout function ) doesn’t mean it will be executed after 0 millisecond, but, it means that it will be moved to callbackqueue after 0 millisecond.
After step 1 ‘world’ is logged on the console and immediately removed from callstack. Since callback queue should wait until callstack is empty, it can’t be executed first. This is why
world is logged before
hello is logged on the console.
Finally when the call stack is empty, the callback function is passed to the stack so that it can be executed. And this happen by something called the event loop. So basically the event loop takes callback functions from the callback queue and puts them in the callstack so that they can be executed.
Thank you for reading and hope this might be helpful to you!!!
reference : video