Asynchronous JavaScript

What is it used for ?

JavaScript is an important language that functions often as an intermediary between a user and a server.  The interface which the user connects to  needs to maintain a processing speed faster than it can communicate with the server.  This is to create a seamless user experience.  If the user interface blocks or pauses at  each server request then the user interface would be very jerky and not through, think about a bad connection on a video conference. 

A quick look under the hood ?

JavaScript is a single threaded engine so to counteract any delay in interaction for the user the JavaScript engine has a main thread which determines the operating of the user interface(in a front end client side application) and a separate thread for storing call back functions.  Without going into too much detail there are two separate queues used to store callback functions these are the call back queue and the micro-task queue.  

The callback and micro task queue  do not execute commands they store the function until the main thread is empty. This is why JavaScript is called a single threaded language because only the main thread can execute commands. The main thread executes each callback function in the order that it was stored in the micro task queue.  There are methods to deliberately use the micro task queue with service workers and worker  threads. 

Example

A while back in an interview I was  asked an interesting question.  If a set timeout method is set to 0 at what stage will the function execute and why.  It's an interesting way of analysing async code even though the timer is set to 0 the function is still executed after being stored in the call back queue.

source code github.com/SiJBC/JavaScript_Fundamentals/tr..