Is it asynchronous or synchronous?
So how do we deal with this? Asynchronous callbacks. These are non-blocking functions in the browser (equally in node) and they are all made asynchronous, which basically means we run some code, give it a callback and run that later. If you have worked with JS, you have also seen asynchronous functions. The most common example is setTimeout. So if we put some code as a setTimeout callback, what the browser does is queueing this piece of code for the future and then skips on to the code that comes next.
Let’s see them in action, step by step, by analysing a small piece of JS code.
Here is what happens in the browser when we invoke the asynchronousExample function:
1) The console.log “A” is being pushed into the stack
2) ‘hi’ is being logged
3) setTimeout is pushed into the stack
4) Its callback is being forwarded into the WebAPI and the API’s timer starts counting for 500 ms.
5) The console.log “C” is being pushed into the stack.
7) When the timer reaches 0, it forwards the callback to the task/callback queue.
8) The event loop checks if the stack is empty and executes the console.log “B”
That’s what the event loop is doing. It makes sure that the method calls that lie into the stack do not conflict with the ones that come from the task/callback queue. The callback queue is just receiving the callbacks from the browser’s Web APIs.
In the following video the execution process is being visualised:
You can watch a visualisation of this process in this beautiful tool made by Philip Roberts:
Experiment with your own functions and see them in action.
Have a great and productive week!