Introduction to Javascript Processes

How do JavaScript processes work?

JavaScript runs as a single threaded process, meaning that it can only do one thing at a time. You can picture JavaScript’s main event loop as a list of instructions, executed one after another. This works nicely, but sometimes we want code to be executed in the background while we continue to execute the main event loop. Enter non-blocking ( usually asynchronous ) utilities. A function is considered “blocking” if the main event loop must wait until it has finished to execute the next command. “Non-blocking” functions will allow the main event loop to continue as soon as they begin and typically alert the main loop once it has finished by calling a “callback”.

Blocking: In this code, once foo() is called, the application must wait until foo() returns before it calls allFinished().

Blocking, With Callback: In JavaScript, all methods are First Class Functions, meaning they are objects that can be passed to other functions as an argument. This allows us to pass a function into another function that will execute it once it finishes ( this is a callback! ). Although using a callback in this way might seem like your code is now non-blocking/asynchronous, it is still blocking since only one thread is managing the event loop. This example shows the use of a callback whilst still blocking.

Non-Blocking / Asynchronous: A truly non-blocking function will return immediately and allow the main event loop to continue execution while it works on it’s task in the background. Typically, callbacks are passed to the non-blocking function for it to execute once it finishes. The most common use of non-blocking JavaScript is AJAX. Here is an example using jQuery’s AJAX utility:

Other uses of non-blocking code in JavaScript include setInterval and setTimeout. These two methods return immediately allowing code to resume, while a timer is set in the background that triggers a callback when it is ready. The callback is pushed back into the event loop stack, executed, and the main loop continues. Animation libraries rely on these utilities to execute bursts of animation between event loop iterations.

This is a brief introduction on JavaScript processes. To learn more about asynchronous JavaScript, be sure to check out node.js.