JavaScript: Asynchronous Programming Primer

Some aspects of JavaScript are well known, or well loathed, mostly because it’s only partially understood. Some of these include that JavaScript is an interpreted language, which is not entirely true, which we’ll save for another day. Another is that JavaScript is a single threaded language, which is true but there are structures which allow more than a single thread to operate.

A city called asynchroni… city

Asynchronous programming allows multi-threading via Web API’s (such as event handlers) that handles processes and return tasks to the browser separately from the main thread.

The cycle follows that when a function or other code is encountered, it is placed on the Call Stack and the stack at this point is unavailable till this code is executed. The Call Stack is the data structure that handles function calls in the order that they were executed, i.e. first in, last out. This stack is the main thread that JavaScript runs on in browser. If, however, an asynchronous function is encountered, the code is deferred to a non Call Stack process to handle,

These other processes run the code, which are sent to it as callback functions, whose results are then queued in the Event Queue. This is eventually passed back to the Call Stack when it is empty. A common Web API that processes such asynchronous calls are Timers, these include:

setTimeout()

The setTimeout() method can be used to put a task on the event queue.  The method takes a callback function as the first argument and the amount of time to wait as the second argument. The time value is numeric in milliseconds. e.g. 500, 1000 which equates to half and one full second,

setInterval()

This is similar to the setTimetout() method however, the call back function will be called non-stop after each time value period lapses.

Stopping Timers

Each method above can be stopped using the related stopping methods:

  • clearTimeout()  // for setTimeout()
  • clearInterval()   // for setInterval()

When the respective timer events are created, it returns a numeric id which can be stored in a variable and then passed on to the methods indicated. This allows targeting a specific timer instance to be stopped.

Conclusion

Asynchronous programming allows processes, which would otherwise tie up the browser and make it unusable to another handler and return the results to the main thread. Thus allowing the application question to be efficient and responsive.

This is just a small primer on the asynchronous capabilities of JavaScript on the browser side. Stay tuned as more write ups will focus on this topic and related areas.