views:

53

answers:

3

If there are 2 or 3 or 20 statements using jQuery's

$(function() { ... })

to add functions to be executed when the DOM is ready, will all those functions run in parallel or run in sequence?

+3  A: 

they will be run in sequence. you can put breakpoints in firebug to see this behavior

ooo
I don't think using breakpoints is a conclusive test. You could put breakpoints for multiple threads in Eclipse using Java for example, and the debugger will stop at each breakpoint. The distinguishing factor there is that the currently executing thread is listed. If that were not the case, then you won't be able to tell so easily if the code is executing in a threaded fashion.
Anurag
+4  A: 

document.ready behaves like a normal event in this respect, they happen in a sequence and in the order they were bound. You can see the relevant jQuery core source here:

This is what happens when you do $(function):

ready: function( fn ) {
    jQuery.bindReady();
    if ( jQuery.isReady ) {
        fn.call( document, jQuery );
    } else if ( readyList ) {
        readyList.push( fn );
    }
    return this;
}

And this happens later, when the "ready" event fires:

if ( readyList ) {
    var fn, i = 0;
    while ( (fn = readyList[ i++ ]) ) {
        fn.call( document, jQuery );
    }
    readyList = null;
}

If the document's already ready, the function executes immediately, that's the if part in the first code block above.

Nick Craver
+3  A: 

They will run in sequence. Javascript code doesn't run in parallel.

Guffa
In this case that's true, but as a blanket statement it's not *entirely* true, [bobince](http://stackoverflow.com/users/18936/bobince) did a great writeup on exceptions here: http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded
Nick Craver
@Nick: That looks more like the execution is interrupted by events in some cases, rather than actually running in parallel.
Guffa
Javascript code doesn't run in parallel? What if you have 2 `setInterval()` one every 0.1 second, and another every 0.11 second, then won't 2 functions run in parallel at some point? (like 2 threads)
動靜能量
@Jian Lin no, the exact timeout / interval is not guaranteed, if the thread is busy (and remember you only have one of them - web workers aside!) it is queud
redsquare