jQuery.when()S2C Home « Core & Internals « jQuery.when()

Execute callbacks on deferred objects representing asynchronous events.

Shorthand version  $.when()

If no arguments are passed to jQuery.when() it returns a resolved Promise object.

Description

The jQuery.readyException() method fires when an Error JavaScript object is thrown synchronously from a jQuery() or jQuery( document ).ready() function or equivalent.

Syntax

Signature Description
jQuery.when( deferreds )Execute callbacks on objects representing asynchronous events.

Parameters

Parameter Description Type
deferredsZero of more deferred objects. Deferred or
Promise
or Thenable.

Return

A Promise object.

jQuery.when( objects ) ExampleTop

Provision to execute callback functions on zero or more Deferred, Thenable or Promise objects objects that represent asynchronous events.

In the following example when we press the left button the first time, we create a plain JavaScript object on the fly and then use the done method on the returned Promise object to send an alert of the object property.

When we press the right button the first time, we create a Deferred object and then fire off some animations. We use the .promise() method which gets resolved when all the animations have completed. After this happens we fire off a message and resolve our Deferred object. This then allows our .when() method to complete and we display a message showing this completion.


$(function(){
  $('#btn1').one('click', function() { 
    $.when({ aProp: 'Hello World. <br>' }).done( function(returnedPromise) {
      $('#div1').append(returnedPromise.aProp); 
    });
  });
  $('#btn2').one('click', function() {
    var ourDeferred = $.Deferred();
    ourDeferred.always( aFunc );
    $('#curry1').fadeIn();
    $('#curry2').slideDown('slow').slideUp('fast');
    $('#curry3').fadeIn(2000).fadeOut('fast');
    $('#curry1, #curry2, #curry3').promise().done(function() {
      $('#div1').append('Animations completed! <br>');
      ourDeferred.resolve( 'Our deferred was resolved. <br>', '#div1' );
    });
    $.when( ourDeferred ).done( function() {
      $('#div1').append( '<code>.when()</code> has completed.<br>'); 
    });
  });

  function aFunc( value, div ){
    $(div).append( value);
  }
});
a picture of curry a picture of curry a picture of curry

Press the button below to action the above code: