Zero Timeout

Provides a way to avoid the user interface from freezing up.

jQuery uses Timeout values of 0 and 1, both of which have the same effect.



Overview


In the Essential Section of this program we discussed the event loop and the Zero Timeout pattern. This pattern is used to give the event loop time to catch up with pending events in the event queue. It an important pattern because it prevents the user interface from freezing up with long running scripts.

jQuery uses this pattern in several places. Here is a code snippet from jQuery's ready method:

// Make sure body exists, at least, in case IE gets a little overzealous.
if ( !document.body ) {
    return setTimeout( jQuery.ready, 1 );
}
// ...

Another instance in the jQuery.ready.promise method:

if ( document.readyState === "complete" || ( document.readyState !== "loading" && 
    document.addEventListener ) ) {   
    // Handle it asynchronously to allow scripts the opportunity to delay ready
    setTimeout( jQuery.ready, 1 );
}
// ...

And here is a snippet from its Ajax functionality:

} else if ( xhr.readyState === 4 ) {
    // (IE6 & IE7) if it's in cache and has been
    // retrieved directly we need to fire the callback
    setTimeout( callback, 0 );
}
// ...

And finally an asynchronous animation example

// Animations created synchronously will run synchronously
function createFxNow() {
     setTimeout(function() {
         fxNow = undefined;
     }, 0 );
     return ( fxNow = jQuery.now() );
}

In jQuery the Zero Timeout pattern is used to address some specific browser peculiarities as well as assist in asynchronous animations. It is interesting to note that both 0 and 1 millisecond are used for the delay. It really does not make a difference because JavaScript's internal minimum is apparently 4 milliseconds.



  Lazy Load
Singleton