Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is jQuery "each()" function synchronous?

People also ask

Is jQuery function asynchronous?

The jQuery Ajax async is handling Asynchronous HTTP requests in the element. It is a procedure to send a request to the server without interruption. It is an Asynchronous method to send HTTP requests without waiting response. It is a function to working on a server without associating more than on request.

Is jQuery post asynchronous?

The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response.

Is jQuery load asynchronous?

From what I know, the load event will always fire asynchronously, except if the image is already cached (in some browsers). The only reliable solution is to put the code in a callback like you did.

Are JavaScript functions synchronous?

JavaScript is Synchronous Spoiler: at its base, JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.


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.


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.


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');
}

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
});