1

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.

10
  • 2
    How is the second example async? It just calls a callback when it's done? Commented May 17, 2013 at 20:51
  • 4
    Merely passing functions around is not what makes the runtime system asynchronous. It's the existence of the event dispatch system and the external services that use it to announce that events have taken place. Commented May 17, 2013 at 20:53
  • Event dispatch system? Seems relevant to what I want to learn about. Commented May 17, 2013 at 20:54
  • 1
    @Dropped.on.Caprica the event dispatch system is the mechanism that does things like operate the timers for setTimeout() and setInterval(), 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. Commented May 17, 2013 at 21:01
  • 1
    Perhaps delving into the specifications would appeal to you? Commented May 17, 2013 at 21:25

1 Answer 1

2

The second version is not asynchronous... the nested function is just calling itself recursively (btw a bad idea with a big array).

To make it asynchronous you should instead for example schedule a timer (with setTimeout) so that the computation will be continued later.

var index = 0;
var total = 0;
function step() {
    if (index < array.length) {
        total += array[index++];
        setTimeout(step, 0);
    } else {
        callback(total);
    }
}
setTimeout(step, 0);

In this case the function would return immediately to the caller and the completion callback will be called later (asynchronously) once the computation is complete.

Internally one way to implement for example setTimeout is keeping an heap of timer events waiting to be fired. When the JS environment has completed current event it will check to see what is to be generated next and then will remove the item from the heap calling the handler.

Note also that in addition to timer events there are mouse events, network events, message events and so on... normally timer events are given the lowest priority so the code gets called only when there's nothing else to do (that's also why timing is not accurate and the delay specified is just the minimum delay).

Even when there are no other events normally JS in a browser for example will first do a DOM repainting if needed before calling timer handlers (and that's why for example a progress bar would update even when processing is performed using setTimeout(f, 0).

Sign up to request clarification or add additional context in comments.

5 Comments

Ok, I get that. However this doesn't get me closer to understanding the internals on how JS handles async code. I get what it does, however the details on that are what I can't seem to find. Everything I search for ends up giving me tutorials on how to use XHR, jQuery, etc.
I added an explanation on a possible implementation strategy for timer events (using an heap for pending timed callbacks). I'm not sure I understand what is the part that you don't understand :-)
@Dropped.on.Caprica - Search for web workers and try to figure out how they work internally, should give you a general clue to how async works, and there should be more information on that as it's newer tech.
Ahh alright, thanks for the additional info. I'm just at a weird point where I know how to code pretty well using JS, but I'm not 100% on the why of everything. I attempted to look up how JS handles asynchronous calls before but couldn't find anything.
@adeneo I'll do just that. Thanks for the tip!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.