Event loop in asynchronous
The event loop in javascript handle what happens behind the scenes in js when you call callback functions, DOM events etc..
How asynchronous works
const second = () => {
setTimeout( () => {
console.log("The end");
}, 2000 );
};
const first = () => {
console.log("Hey there !");
second();
console.log("It's ok !");
};
first();
- In the execution stack we add on top the
first execution contextwe now execute the code inside of this function, the first line is called so in the console you should now havehey theredisplay. Then we call thesecond functionwe now put on top of the execution stack thesecondfunction. - We call the
setTimeoutfunction so we now have on the top of the execution stack thesetTimeoutfunction, but as you can see this function has a callback function which means she will be run asynchronously after 2s because of the second argument2000. - What happen now ? We don't execute the code directly when the function is called because she's need to run asynchronously so the function will be moved into the
Web api environment, from now the function will be running in the background of our code and we can keep going executing the code so we can remove thesetTimeout execution contextand also thesecond execution context. - Back in our
first execution contextwe can execute the last line of code and now our console should havehey there it's ok. Right now all our synchronous code was executed we can now be focus on our asynchronous code. - Let's say that 2s are passed so our
setTimeoutfunction can now be executed so she will be moved to themessage queue environment. - This environment hold all the functions who's waiting to be push in the
execution stackas soon as this one is empty, in our example ourexecution stackis empty and ourmessage queueenvironment contains thesetTimeoutfunction so we can push this one in theexecution stack. - Our execution stack is now on top
setTimeoutfunction so we can execute the code inside this one and our console should now displayedhey there it's ok the end.
Current errors
This is a list of the main errors that you can meet:
Note: I'm not a wizard there is maybe some issue that you notice above so fell free to open an issue in the github repo if you find a new error not mentioned above.