EDIT - Js fiddle link to script file - http://jsfiddle.net/r4uH3/
EDIT 2 RE ACCEPTED ANSWER Although question already closed, thought I would add some detail on why I accepted the answer below.
Also see this re why original code didn't work - How do I return the response from an asynchronous call? - it's points re AJAX are not literally related, but the explanation of asynchronicity is important to understand.
Fabrício Matté's answer works perfectly for me, although I adapted it slightly:
(function($){
// some pre-iteration stuff here
// iteration vars
var elementIndex = 0;
var collectionLength = this.size();
var ts = this;
// THIS IS THE KEY BIT AS PER ACCEPTED ANSWER
// RATHER THAN USING THE NORMAL "this.each"
(function initLoop(){
// check if got to last element
if (elementIndex < collectionLength){
// DO STUFF, WHATEVER, AS LONG AS YOU DON'T EXPECT
// ASYNCHRONOUS FUNCTIONS LIKE AJAX / TIMERS NOT TO, WELL, EXECUTE ASYNCHRONOUSLY UNLESS YOU HANDLE THEM PROPERLY!!
// AND FINALLY - GO TO NEXT ELEMENT IN COLLECTION
initLoop();
};
})());
})(jQuery);
The other thing that helped, although not exactly related, was using global and element-specific variables stored using jQuery(el).data();
rather than using window.VARIABLENAME
or MyNamespace.VARIABLE_NAME
. Eg:
// outside of iteration
jQuery(window).data("GLOBAL_STUFF", { /* add properties here and set them later*/ });
var globalData = jQuery(window).data("GLOBAL_STUFF");
// inside iteration
jQuery(currentElement).data("ELEMENT_DATA", { /* add properties here and set them later*/ });
var elementData = jQuery(window).data("ELEMENT_DATA");
// then set props like so (obviously get, similarly..)
globalData.someArrayOfSomething.push(something);
elementData.someBooleanValue = true;
Again, thanks to Fabrício.
I have written a jQuery plugin that, like most, can be executed on multiple (i.e. a collection of) elements.
in the
this.each(function(i,el){ });
part of the function, I create a new instance of another object type (nothing to do with jQuery) and call its "Init" method.I expect, with the .each loop, that it will loop to the next instance after the init method has been fully executed.
I am not using any async (AJAX / timers) anywhere.
I am using callbacks always on anything like "jQuery.fadeIn" or similar.
THE PROBLEM
The Init methods are called virtually in parallel. They do not complete their execution before the next one is called.
Can anybody advise of any known issues? Is there something I'm missing from the above "theory"?
Using jQuery 2.0.