What am I asyncing about!

Paul Zietsman
5 min readApr 20, 2017

Originally published at codemonkeyman.blogspot.com.

When I started with Javascript, I was oblivious to its asynchronous ‘nature’ (to mention one) and what exactly that meant to me as a programmer?? As I started hacking away at the forest that is JS tutorials, it came to my attention that there is a bit more to JS than simply updating a DOM element!?!

Terms like single threaded, non-blocking IO and asynchronous events were being thrown around and it took me a good while to get to grips with them. The purpose of this post is to reaffirm my understanding of these concepts and hopefully help someone else through their journey of JS discovery. Before we start, lets look at simple example to demonstrate some of this craziness.

the code*
zero ms timeout?

The output right? I mean the timeout hit at 0 ms, the loop started and finished? Easy! But wait, look what we are seeing in the console?

zero ms timeout!

Why would this be?!

Enter the path of THE SINGLE THREADEDness!

JS being single threaded means your ‘code path’** has been set and only once you have finished this path, other triggered events will be executed.
So what happened here!? Is setTimeout*** not in our code path? It definitely is, but its callback function is not exactly there…

STOP! Just kidding, I’m non-blocking IO

Let’s forget about, what happened to our callback for a second and focus on what does non-blocking mean?
Before looking at non-blocking, what is blocking code? In our example we have a prime example of blocking code. That nasty while, will prevent ANY other code form executing while it is busy. This includes any button presses, animations or ANYTHING on your webpage requiring JS to function properly.

Shoot! Okay so blocking code can be very bad. So then non-blocking code, must be code that allows other code to execute in parallel. Exactly-ish! But wait, that sounds a lot like multi-threading? And this is where that all important little IO comes into play. Functions that access processes outside the ‘javascript-world’ are non-blocking, these include file system processes, making http calls, and setting timers.

“…unlike a lot of other languages, (Javascript) never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input. “ — The Mozilla

Cool! This means I can pass that awful loop to another service and not kill the rest of my app? Jip, you definitely can and it might look something like this.

non-blocking our while

So the non-blocking and callback mechanism helps us overcome some of the limitations that comes with a single-threaded environment. Now we have processes running in parallel, but how do we catch and consume the results? Enter async events!

Being there, but not being there, ASYNCHRONOUS EVENTS?

Okay so setTimeout is in our code path, but the callback is not? What happened to our callback, where is it? As we saw, these non-blocking methods run in parallel with our code and the callback is the ‘handle’ we are given to grab the results of this parallel action.
setTimeout
registers an event listener, in this case when a specified timer runs out. When this event gets triggered, our callback function gets put in a ‘end-of-your-code-path’ queue (or just the queue). As the name gives away, this queue only gets ‘serviced’ once the current code path is completed. The items in the queue creates new code paths and any callbacks that spawns from them, eventually ends up in the queue. This cycle will continue until there are no more items in the queue and all the enlisted event listeners are killed off, otherwise the application will continue with this loop of listening and reacting to these events. One might even call this loop the EVENT LOOP
Remember, events end up in the queue not by when they were created, but by when they were triggered!

Some Mary

With what we have observed, lets look at what happened in the code example.

the path

JS started executing code from the top of the stack, working its way down. Firstly setTimeout registered an event listener with an anonymous callback function. Almost immediately the timeout event gets triggered, adding the callback in the queue AND that is it for the callback. Secondly we console out that the while is about to start. Next the we kick-off the loop running for 1000ms. We finish of the process by console-ing out that the loop has finished in record time! Now that the stack is empty, the JS runtime fetches the first callback from the message queue and start executing it, and now we see the ‘0ms timeout?!’ message on the console. Easy!

Spot any mistakes or have any feedback? Please comment and we’ll build something awesome!

*Technically there is no such thing as a 0 ms timeout, browsers implement a minimum timeout (4 ms).

** Also known as the stack.

*** For the purpose of this write-up, setTimeout will serve as the archetype for all IO methods that is and will be!

--

--