Is jQuery "each()" function synchronous?

JqueryAsynchronous

Jquery Problem Overview


consider this scenario for validating:

function validateForm (validCallback) {
   $('#first-name').add($('#last-name')).add($('#address')).each(function () {
      // validating fields and adding 'invalid' class to invalid fields.
   });
   // doing validation this way for almost 50 fields (loop over 50 fields)
   if ($('#holder .invalid').length == 0) {
       // submitting data here, only when all fields are validated.
   }
}

Now, my problem is that, the if block get executed before loops are finished. I expected the body of validateForm to be executed synchronously, but it seems that jQuery each() function gets executed asynchronously. Am I right? Why this doesn't work?

Jquery Solutions


Solution 1 - Jquery

Yes, the jQuery each method is synchronous. Nearly ALL JavaScript is synchronous. The only exceptions are AJAX, timers (setTimeout and setInterval), and HTML5 Web Workers.
Your problem is probably somewhere else in your code.

Solution 2 - Jquery

jQuery is purely a javascript library. Except ajax, setTimeout and setInterval there is nothing that can asynchronously executed in JavaScript. So each is definitely executed synchronously. There is definitely some js error inside the each block code. You should take a look in the console for any errors.

Alternatively you can take a look at jQuery queue to execute any function in the queue. This will make sure the queued function will be executed only when the previous code execution is complete.

Solution 3 - Jquery

Another reason to ask that question would be that .each will simply stop iteration when the (.each() ) function returns false, and an additional variable must be used to pass the "return false" information.

var all_ok=true;
$(selector).each(function(){
    if(!validate($(this))){
        all_ok=false; //this tells the outside world something went wrong
        return false; //this breaks the .each iterations, returning early
    }
});
if(!all_ok){
    alert('something went wrong');
}

Solution 4 - Jquery

For me it works like asyncronous. If it works sync, why it works like that:

var newArray = [];
$.each( oldArray, function (index, value){
		if($.inArray(value["field"], field) === -1){
			newArray.push(value["field"]);
		}
	}
);

//do something with newArray here doesn't work, newArray is not full yet

$.when.apply($, newArray).then(function() {
	//do something with newArray works!! here is full
});

Solution 5 - Jquery

return false in .each() function breaks the loop only, and the remaining code outside the loop still executes. So set a flag in .each() loop and check it outside the loop.

Solution 6 - Jquery

Same problem. So i fix like this

var y = jQuery(this).find(".extra_fields");
for(var j in y)
{
    if( typeof  y[j] =='object')
    {
        var check = parseInt(jQuery(y[j]).val());
        if(check==0){
            jQuery(y[j]).addClass('js_warning');
            mes="Bạn vui lòng chọn đầy đủ các thuộc tính cho sản phẩm";
            done=false;
            eDialog.alert(mes);
            return false;
        }
    }

}

Solution 7 - Jquery

Thats how i do it

 function getAllEventsIndexFromId(id) {
    var a;
    $.each(allEvents, function(i, val) {
        if (val.id == id) { a=i; }
    });
    return a;
 }

Solution 8 - Jquery

I had the same issue. my $.each was inside the success function of ajax call. i made my ajax call synchronous by adding async: false and it worked.

Solution 9 - Jquery

The jQuery.each method loops Synchronously, but you can't guarantee that it'll loop through the items in any specific order.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaeed NeamatiView Question on Stackoverflow
Solution 1 - JqueryAbrahamView Answer on Stackoverflow
Solution 2 - JqueryShankarSangoliView Answer on Stackoverflow
Solution 3 - JqueryMorg.View Answer on Stackoverflow
Solution 4 - JqueryTuitxView Answer on Stackoverflow
Solution 5 - JqueryM HussainView Answer on Stackoverflow
Solution 6 - Jqueryuser3027521View Answer on Stackoverflow
Solution 7 - JqueryMiguelView Answer on Stackoverflow
Solution 8 - JqueryNilkamal GotarneView Answer on Stackoverflow
Solution 9 - JqueryChris PietschmannView Answer on Stackoverflow