General question about multithreading / non-sequential execution of JS code
I've been writing JS for years and have often encountered situations where I had to stick code in setTimeout()'s in order for it to function the way it "should". This has always left me a little puzzled but I never got round to asking about it. Well, this problem just cropped up again and this time I really have to figure out what's going on.
Here's a really simple example for illustration purposes (which I think is valid). Imagine the first line takes half a second to complete, and when it's done it dumps some HTML into "myid". Inside the HTML is a textfield with an ID of "myinputfield".
When that runs, unless you stick the second line in a timeout, you (could) get an error since it doesn't think the ID exists.
document.getElementById("myid").innerHTML = mystr.replace(/some complicated regexp/g, str);
document.getElementById("myinputfield").value = "something";
So what's going on here, exactly? Where's the lag happening?
Surely JS should execute statements sequentially, running one statement after the next - always. Is there some sort of JS engine optimization going on in the browser that lets it think that maybe those statements aren't related, so it doesn't wait for the first to complete before executing the second?
I'd really like to identify the situations in which problems like this can occur, so I can plan for them. Up to this point I've just been working empirically; write some code, check in the browsers. Write some code, check in the browsers. Pretty daft.
Any information you could provide would be very welcome!