Asynchronous Function Callbacks using Javascript

Taking a quick break from System Architecture for a bit, right now I’m in the mood for some (asynchronous) function callbacks using Javascript. A clear understanding of this will help any javascript developer in understanding the dynamic language we all have grown to wrestle with – Javascript.

I’m going to dive into a basic example of a function utilizing a function callback.

Function Callback (example)


function calc( num, callback ) {
        return callback( num );
}

var addTen = function( num ) {
        return num + 10;
}

var answer = calc( 3, addTen);

console.log(answer); 

// Output: 
// 13

Above is a nice basic example of what a function callback would look like. If you used jQuery in your web development, you may have crossed using a callback without even knowing it.

Alright, on to asynchronous callbacks

Asynchronous

Let’s first get a basic definition of what asynchronous means. It simply means “More than one at at time.” A more rudimentary explanation of this can be achieved by imagining a chain reaction. When one a function is called, it executes another function while the previous function is still running.

But Javascript fundamentally is synchronous, NOT asynchronous. So how is this possible?

The Javascript Engine

To understand how Javascript is able to do this, we must first understand that Javascript is powered by an Engine of additional components – most of which we often forget that’s there. This is often running in the background so it’s hardly noticeable.

There are other “engines” that make up the Javascript Engine as a whole.

– Render Engine – painting
– HTTPRequest – getting data
– Event Queue

To understand asynchronous callbacks, we need to dive in deeper into the Event Queue. This is where all events are registered, like a ‘click’ event. It is important to understand that the Event Queue isn’t processed until the execution stack is empty. In other words, only after every function has completed.

So the Javascript Engine creates the illusion that processes are occurring asynchronously, however the only thing that is happening asynchronously are the event handlers being pushed into the event queue for later processing in the order they are received.

Below is a piece of code that emulates a rocket launch along with a function to keep track of its count down.


        // function for rocket launch count down
        function rocketTakeOff() {

                var ms = 5000 + new Date().getTime();
                while (new Date() < ms) {}

                console.log('finished count down');

        }

        function launchRocket() {
                console.log('button pressed for launch');
        }

        // listen for the click event
        document.addEventListener('click', launchRocket);

        rocketTakeOff();
        console.log('finished execution');

So what would you expect from this piece of code? Well when we run the program in the browser and simultaneously start clicking anywhere on the page, we’ll find that “button pressed for launch” will always appear last.


finished count down
finished execution
button pressed for launch

So after 5 seconds, the rocketTakeOff() function will fire first and then this line – console.log(‘finished execution’).

Any registered event handlers will execute last, only after the execution stack is empty no matter how early you start clicking (anywhere, in this case) on the page.

I think this is an excellent intro in understanding function callbacks and asynchronous ones as well, or how the Javascript Engine creates the illusion that it is asynchronous. Just wanted to cover this concept before I get back to my series in System Architecture. Stay tuned, and keep immersing yourself.