Understanding how $ .promise works similar to transitionEnd

I was just messing around on the documentation page jQuery.promise()

and came across the following piece of code:

$("button").on("click", function () {
    $("p").append("Started...");

    $("div").each(function (i) {
        $(this).fadeIn().fadeOut(1000 * (i + 1));
    });

   $("div").promise().done(function () {
        $("p").append(" Finished! ");
    }); 
});

      

FIDDLE HERE

Now I understand that $ .defer in jQuery helps with asynchronous programming, also I understand that $ .done and $ .fail are part of the $ prom object.

I read an interesting article HERE . There are some good examples of how $ .defer can be used to monitor css-3 transitions.

However, in the example script I provide, I don't understand how $ .promise brings up the fact that the transition is complete. How does it promise to know that the completion of fadeout () is complete?

How does this piece of code work?

$("div").promise().done(function () {
            $("p").append(" Finished! ");
        }); 

      

How does the promise really work here? Can someone please explain?

+3


source to share


2 answers


Simply put, jQuery creates a queue of deferred objects for each object returned by the selector $("div")

(visible through the function .data()

).
When you add some CSS animations to a div with jQuery functions like fadeIn()

or fadeOut()

, it creates deferred objects that are added to each individual queue. Using $("div").promise().done()

on the parent collection allows you to check if all the child queues are omitted (jQuery will iterate over the children elements).



+2


source


I haven't delved into the jQuery source, but here is my understanding.

$. a promise returns a promise that ends when all actions of a particular type have completed. The default is "type" fx

( source ). When the queue is fx

empty, the promise will be resolved.



In your script, you call fadeIn()

which adds animation to the queue fx

. ( $.fadeIn()

by default has queue: true

.) $.fadeOut

does the same.

When the queue is empty, the promise will be resolved. This script will support this. (The queue is "inprogress" while the animation is running, but is empty after 100m.) A bit more confusing fiddle - notice how the promise ends when we clear the queue fx

using $(el).queue('fx',[]);

?

+1


source







All Articles