# Asynchronous JavaScript


<h4>What is it used for ?</h4>



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



<h4>A quick look under the hood ?</h4>



<p>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.&nbsp; 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.&nbsp;&nbsp;</p>



<p>The callback and micro task queue&nbsp; 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&nbsp;can execute commands. The main thread executes each callback function in the order that it was stored in the micro task queue.&nbsp; There are methods to deliberately use the micro task queue with service workers and worker&nbsp; threads.&nbsp;</p>



<h4>Example</h4>



<p>A while back in an interview I was&nbsp; asked an interesting question.&nbsp; If a set timeout method is set to 0 at what stage will the function execute and why.&nbsp; 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. </p>



<p>source code https://github.com/SiJBC/JavaScript_Fundamentals/tree/feature/Async_Callbacks</p>

%[https://youtu.be/qcwVpKcgo0Y]


