Asynchronous Javascript / Order of Execution

Most people are used to seeing their code run sequentially but with Javascript, some code runs asynchronously. This can produce some confusing results. There are 2 cases when code would run asynchronously:

  1. when making an AJAX call, e.g. $.ajax, $.getJSON, $.getScript, etc
  2. when an “event” occurs, e.g. on load, on click, on blur, etc

In the first case, if you make an AJAX request, that initiates an http request which may take some time to complete. Here’s an example:

[cc lang=”javascript”]
var a = 0;

$.getJSON(‘somefile.json’, function(data)  {
a = 2; // this block of code executes on success and is the same as the following “success” callback
}
.success(function(data) {
a = 2;
})
.error(function() {
a = 3;
})
.complete(function() {
a = 4;
});

console.log(a);
[/cc]

When you run this, the value of  a will be 0 because when the getJSON call is made, a new process is spawned and the first process continues and reaches the console.log(a) call before the AJAX call completes. If you want code to execute AFTER the AJAX call is made, you must put your code in a callback such as “success”, “error”, and “complete”. If the AJAX call is successful, the code in the success block will execute. If the AJAX call fails, e.g. if the file is not found, then the code in the error block will execute. The code in the complete block will execute after the success or error blocks execute.

In the second case, if you attach code to execute when an event occurs, then that code will not run until that event occurs. For example,

[cc lang=”javascript”]
$(document).ready(function () {
var a = 0;
$(“#target”).click() {
var a = 1;
});

console.log(a);
});
[/cc]

In this example, the console will show the value of a equal to 0 as soon as the document is ready even though the call to console.log comes after the call to $(“#target”).click(). The value of a will only become equal to 1 after the user clicks the element with ID target.