One of the stand-out features of JavaScript (or detriment, depending on your views on the subject) is it's asynchronous nature. I understand how the code flow works, but I'm not 100% on what makes asynchronous code "asynchronous".
Sure, contacting servers or reading/ writing to a database is an asynchronous action. But what about something normally handled non-asynchronously? I can write code that uses callbacks to make it asynchronous all day.
Sync Example
var arrayToIterate = [1,2,3,4,5,6,7,8,9, ... ]
//Say this array length is in the hundreds of millions.
var addArrayContents = function(array) {
var total = 0;
for (var i = 0, len = array.length; i <= len; i++) {
total = total + array[i];
}
return total;
};
var arrayTotal = addArrayContents(arrayToIterate);
Async Example
var arrayToIterate = [1,2,3,4,5,6,7,8,9, ... ]
//Say this array length is in the hundreds of millions.
var addArrayContents = function(array, callback) {
var iterator = function(total, arIndex, cb) {
if (arIndex == array.length) {
return cb(total);
}
total = total + array[arIndex];
arIndex++;
iterator(total, arIndex, cb)
};
iterator(0, 0, callback);
};
addArrayContents(arrayToIterate, function(result){
console.log(result);
// Do stuff
});
As you can tell, both functions do the same thing, one's asynchronous, one's not. Is there a rule of thumb on deciding the best time to do something asynchronously over synchronously? In the above example, the synchronous function would snag when adding those numbers together, whereas the async version wouldn't hang while running.
I just have a feeling that I don't 100% understand asynchronicity. It seems like it has to be more than looking at a function and finding out if it uses callbacks.
setTimeout()andsetInterval(), handles translating user activity into events in a browser (like "click" and "keypress"), and allows response to network activity (the XMLHttpRequest callbacks). It's a system that's outside the language proper; it's part of the runtime system but it really doesn't have direct impact on the language syntax or semantics.