Great UI experience? Say thanks to the event loop and his “friends”

Philip Roberts: What the heck is the event loop anyway? | JSConf EU 2014

In his talk at JSConf EU 2014 Philip Roberts gave an amazing explanation of how async callbacks are executed in the browser and who are the players in the game.

Being the JS runtime single threaded your code is executed one piece at the time in the call stack. Only after the completion of one task the next one can be executed. You could ask yourself: “Ok one task at the time what’s wrong with that?” Well…if that task takes a long time to execute during that time your browser is stuck you can’t do anything you have to wait for its completion.

To solve the problem asynchronous callbacks functions come to help. Thanks to the various WebAPIs and data structures provided by the browsers we can delegate the execution (have multiple threads) of our time consuming task and give him what is called a call back function. In doing so the we can start our blocking task but we don’t have to wait its completion we can continue to execute the rest of our synchronous program in the call stack. Once our blocking task has completed the WebAPI is responsible to push the associated callback function in the callback queue provided by the browser and the event loop will push it to the call stack (ready to be executed) once it’s empty . The only scope of the event loop is to look for callback functions in the callback queue and push them one at the time in the stack.

Checkout Philip’s creation “Loupe. It will help you understand how JavaScript’s call stack/event loop/callback queue interact with each other.

Thanks to the event loop and “his friends” async programming is brought to the JS world and I couldn’t be more excited about it!