JavaScript & jQuery Tutorials

JQ Home Right Arrow Core & Internals Right Arrow jQuery.when()

jQuery.when()

Execute callbacks on objects representing asynchronous events.

Shorthand version $.when()

Description

The jQuery.when() method allows provision to execute callback functions, on Deferred objects or PlainObject JavaScript objects that represent asynchronous events.

Syntax


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

Parameters


Parameter Description Type
objectsOne of more Deferred objects or a PlainObject JavaScript object.Deferred or
PlainObject

Return

A Promise object which is just a copy of a Deferred object without any notify/resolve/reject methods.


jQuery.when( objects ) Example go to Core Core   go to top of page Top

Provision to execute callback functions, on Deferred objects or plain JavaScript 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:

             

Related Tutorials

jQuery Basic Tutorials - Lesson 2 - jQuery Core & Internals



  

go to jQuery home page jQ Home go to Core Core go to top of page Top