Until prepareLayer() , until prepareLayer() does something asynchronous (e.g., AJAX or animation), each loop loop cannot be completed until prepareLayer() until prepareLayer() is complete and your code is already there carry out what you want.
FWIW, if there are no additional operations or parameters in your existing .each loop, you just need to write this:
$('.element').each(prepareLayer);
those. there is no need for an additional shell of an anonymous function.
On the other hand, if it does something asynchronous, use deferred objects:
var def = []; $('.element').each(function() { // have prepareLayer return a _promise_ to return def.push(prepareLayer()); }); function prepareLayer() { var jqxhr = $.get(..., function() { // do stuff with content }); return jqxhr; } // use "when" to call "postPreparation" once every // promise has been resolved $.when.apply($, def).done(postPreparation);
source share