The Event Loop
The Event Loop Behavior
What's the execution order of this code?
And in this case?
How the event loop works
Register a listener : Most asynchronous tasks requires the definition of a callback function in order to retrieve the result of the processing or simply in order to know that the processing ended. During this step, we explicitly or implicitly subscribe a listener to some event source. Examples:
setTimeout
,addEventListener
etc...Add the function to the queue: The callback function cannot be called immediately when the result is received as the thread might be busy executing another function. In the example below, both callback functions are ready to be called the thread is busy executing our
main
function. The JavaScript engine adds references to the callback functions at the end of the callback queue in order to be called once the thread is free.Tick : When the
main
function execution ends, the thread won't have time to stay idle and will immediately grab the callback at the top of the queue and execute it. More precisely, this is the event loop which simply loops forever executing every function in the queue. The moment where the event loop ends the execution of a function and is ready to grab the next one is called a "tick".
Last updated