Understanding Javascript’s Asynchronous Code

One of Javascript’s strength is the way it handles asynchronous (async) code. Instead of getting blocked, the thread is pushed in an event queue which gets fired after the execution of all the other codes. This means that you can let your code do several things at the same time without stopping or locking your main thread. Beginners, however, find it difficult to fully grasp the full potential of async code.
Below is a brief discussion that will help you understand the basics of asynchronous code.Understanding Asynchronous Code

The setTimeout and setInterval functions

The two most basic async codes of Javascript are the setTimeout and setInterval functions.
The setTimeout function is used to execute a specified function after a given time interval. It accepts two arguments: the callback function and the time (in millisecond). Here’s a sample code snippet:

Console.log( “a” );
setTimeout(function () {
Console.log( “c”)
}, 500 );
setTimeout(function () {
Console.log( “d” )
},  500);
setTimeout(function () {
Console.log( “e” )
},  500);
Console.log( “b” );

The code above will result with the console displaying “a” and “b” first, then after 500 milliseconds, “c”, “d” and “e” will be displayed.

Note that a timeout will only be executed after all the code in a block has finished executing. I f along-running function is set before the timeout then the function will have to finish executing first before the setTimeout function gets executed. Basically, async functions like setTimeout and setInterval are pushed into a special queue known as the “event loop”.

The event loop

The event loop is a special queue for callback functions. When an async code is executed, a callback is then pushed into the queue. The Javascript engine will only execute the event loop if the code after the async function has finished executing. Meaning, contrary to what most believe, Javascript is not multi-threaded.

The event loop is a first-in-first-out type of queue – callbacks are processed in order they were added to the queue.

Callbacks

Callbacks are functions that are passed as the last parameter to an async function. It is later called with either a return value or an error message that your function produced.

Common asynchronous code mistake

One of the most common mistakes in Javascript is the use of async code as shown in the code snippet below:

for( var j = 0; j < 5; j++ )
{
        setTimeout ( function () {
console.log(j);
}, j);
}

This function will output:

5
5
5
5
5

The erroneous output is returned because j is incremented after each timeout is created. Then when the callback function is called, it looks for j’s value which is always 5. The solution to this is to create is add some arguments that would store the current value of j. Below is the code snippet for the solution:

for( var j = 0; j < 5; j++ )
{
        (function (j)  {
setTimeout(function () {
console.log(j);
}, i);
} ) (j);
}

The correct output is:

0
1
2
3
4

Image by Sebastian Fuss (flickr)

Article By: Wasim Ismail

Wasim’s a project manager at Alrayes Web Solutions along with an online SEO consultant & blogger for business at wasimismail.com, specialising in online business.


Comments are closed.

Three Measures To Keep Track Of A Cell Mobile Phone appforspy.com mobile tracker app