Can I use the Deferred object to create a callback after the for loop completes?

I have a for loop that fades out in everyone, what I want to do is wait until the last face has completely disappeared and then continue the code that looks like a callback, but I'm not sure how to do it? I thought I could use the deferred object?

Js

var newArray = [3,2,6,4,0,1,5]; for (var i = 0; i < newArray.length; i++) { var dfd = $.Deferred(); $(this).eq(newArray[i]).fadeIn(i * 500); dfd.resolve(); //.. continue with callback code?? } 
+4
source share
2 answers

You can use $.when : passing Delays from all of your fadeIn calls to it, you can register a callback for being executed only when all of them are being executed:

 var deferreds = []; for (var i = 0; i < newArray.length; i++) { var dfd = $(this).eq(newArray[i]).fadeIn(i * 500); deferreds.push(dfd); } $.when.apply($, deferreds).then(function() { ... }); 

Working example in jsFiddle . Note that you can use the return value of fadeIn as Deferred .

Update: since you want each fadeIn start only after the last has ended, Bergi's answer might be more appropriate. An alternative (easier IMHO) could be:

 var i = 0; function f() { if ( i < newArray.length ) { $(this).eq(newArray[i]).fadeIn(i * 500, f); i++; } else { // Your "done" callback, if any } } f(); 

Job example . I stuck to your source code (each effect uses a different duration), but if you want all of them to have the same one, delete i * and just use 500 .

+6
source

I do not think that Deferries will be very useful here. Of course, you can get .promise() for each queue [effect] in jQuery instances, and because of this method, you can even pass jQuery objects to $.when , but I think the callback chain is also for sequential animations, which you need some chain - can make it easier:

 function chainedFadeIn($el, order, callback) { if (!order.length) return callback(); $el.eq(order.shift()).fadeIn(500, function() { chainedFadeIn($el, order, callback); // notice we removed the first element }); } chainedFadeIn($(this), [3,2,6,4,0,1,5], function() { // do something }); 

Alternative version with Promises:

 function getFadeInChain($el, order) { if (!order.length) return order; // or anything else return $el .eq(order.shift()) .fadeIn(500) .promise() .then(getFadeInChain.bind(null, $el, order)); } getFadeInChain($(this), [3,2,6,4,0,1,5]).done(function() { // do something }); 

Demo on jsfiddle.net: Callbacks, Deferred

+1
source

Source: https://habr.com/ru/post/1447754/


All Articles