Wait for a timeout
or how the ugly pause turns into a beautiful in-line swan

Imagine you have a long jQuery invocation chain, and now you want that at some point the invocation waits for short moment (500ms) before continuing.

$('.some').show().children().doThat() .doSomething().hide();
              /* insert a pause here ⇑, please */

With classical tools you now have to split up your chain and put the second part into a new callback function:

$('.some').show().children().doThat();
/* inserted a pause here */
window.setTimeout(function(){
      $('some').children().doSomething().hide();
   }, 500);

You see it, right? Yes, the code gets ugly! No one asked for a reorganization of your code – just a stupid little pause.
Imagine what happens if they now want one more pause at another step, and then another one – aarrgghh!

The solution available in deferred jQuery chain style is a nice timing method called "wait":

$('.some').show().children().doThat() .wait(500) .doSomething().hide();
             /* inserted a pause here ⇑ */

Want another pause? Fine! Just insert .wait() where you want.

Where is the setTimeout() gone?

As mentioned on the previous page all the method calls after .wait() are collected and invoked later. jquery-timing internally still calls setTimeout() but it uses a generic function that will just continue your invocation chain when triggered by the timeout.

Waiting for other things

The same mechanism like for pausing a while can also be applied to any other occasion of deferred callback functions. Let's take a look from an abstract point of view:

The JavaScript concept of deferred callback functions always works like this:

// do something
someObject.someMethod(...,myCallbackFunction,...);
// do something

What we have to do in our timing method is to recognize which kind of registration the developer wants. Then we stop the invocation chain and register a generic function which will continue the chain when triggered.

The current implementation of jquery-timing supports timeouts, animations, events, the .load() function, and deferred objects as registration.
If you want you can use the jQuery event mechanism or a jQuery.Deferred object to wait for any other trigger you like.

Break the waiting

In many cases jQuery allows to unregister your methods again. E.g. .bind() and .unbind(), .on() and .off(), .live() and .die(), or .delegate() and .undelegate().

Our .wait() method also has a counterpart – .unwait(). Any element on which .unwait() is called will stop waiting for any corresponding trigger from .wait(). Thus the deferred jQuery chain will not continue for those elements. (Actually there is an option to continue with unwait, but see that on the details page…)

Instant invocation

When waiting for a deferred object you can have the case that the deferred is already resolved. In that case the invocation chain continues instantly. That means that the invocation of your code behaves as if there was no wait.