jQuery.when() JQ 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.when() method allows provision to execute callback functions on zero or more Deferred, Promise or Thenable objects that represent asynchronous events.

Syntax

Signature Description
jQuery.when(deferreds)Execute callbacks on zero of more deferreds representing asynchronous events.

Parameters

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

Return

A Promise object.

jQuery.when( deferreds ) Example Core  <<  Top

Provision to execute callback functions, on deferreds 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:

             

Related Tutorials

jQuery Basic Tutorials - Lesson 2 - jQuery Core & Internals