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:
- when making an AJAX call, e.g. $.ajax, $.getJSON, $.getScript, etc
- 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]
Continue reading Asynchronous Javascript / Order of Execution