Is jQuery’s each() function non-blocking?
In the below example, I expect “test in each” to be logged first, but in each test “test out of each” is logged first.
So this is causing the loop to run up to the body (sometimes the document) element before returning an error.
I’m just trying to get a common parent to wrap or if the two elements (firstp and lastp) are the siblings, then wrap those.
But, I’m mostly curious about the performance of the each() function and whether it is non-blocking.
while(firstp[0] !== lastp[0]){
//If parents are siblings, this will do for wrapping.
var isS = false;
firstp.siblings().each( function(index, el){
console.log("test in each");
if(jQuery(el)[0] === lastp[0]){
isS = true;
return true;
}
});
console.log("test out of each");
if(isS === true){ break; }
firstp = firstp.parent();
lastp = lastp.parent();
}
EDIT:
Sorry guys. This was a false alarm. Paul is correct. My HTML actually had two elements that was matching for firstp. I didn’t realize this, so the first one did not have a sibling, causing the error. I was looking at the second element the whole time.
But, I did learn something in the process, so thanks for taking the time to answer.
.each()is synchronous. My guess is this:On the first iteration of your while loop firstp has no siblings so the object being iterated by each is empty and “test out of each” is the first thing logged. Then on the second iteration firstp has siblings so it enters the each and you immediately see “test in each” being printed after “test out of each”.
I think you will see the proper behavior from console if you change your code to something like this, so you can see what iteration the loops are on: