I have a very strange bug, what appears to be a race condition makes a width();
call give different results.
I have this jQuery after call:
this.after(
"<div class='menuItemContainer'>" +
"<div class='menuItemTitle'>" +
$("option:selected", this).text() + "<span class='menuItemDownArrow'>▼</span>" +
"</div>" +
"<div class='menuItemList'>" +
selectionMarkup +
"</div>" +
"</div>"
);
In which I insert html into the DOM.
Next I need to know the combined widths of an element with the class menuItemColums
and make their parent div that width.
This markup exists in the variable selectionMarkup
.
To do this I do the following:
var w = 0;
$(".menuItemColumn").each(function(){
w += $(this).width();
console.log($(this));
console.log(w);
});
$(".menuItemList").css({
width: w}
);
This works exactly as expected around 70% of the times, but sometimes I get the wrong measure for some of the elements, or at least for sure the first one sometimes is wrong.
The weird part is that the object seem to be correct, and it's properties are the correct width, but the given widht()
which is assigned to w
is incorrect:
That image, just to clarify shows the result of logging w
and the $(this)
which should be the same, since $(this)
's width property seems to be the correct one.
I kept debugging and found out two things that lead be to believe that this is race condition:
If I execute the last piece of code I posted you again, when the bug is reproduced, it fixes the problem.
If I do the following calls, the give me different results, one incorrect and the other one (second one) correct:
console.log($(".menuItemColumn:first").width());
setTimeout(function(){console.log($(".menuItemColumn:first").width());},3000);
I was under the impression that the second part of the code will not execute until the first one is finished, what gives here?
Note: I'm not 100% sure that race condition is the word I was looking for, but still, the idea is that.
UPDATE:
As @WereWolf-TheAlpha the output of the console doesn't seem like jquery objects, I now can't reproduce that and I'm only getting this:
Without changing any code.