General question about multithreading / non-sequential execution of JS code

The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Threaded View

General question about multithreading / non-sequential execution of JS code

Hi folks,

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.

So what's going on here, exactly? Where's the lag happening?

I've read that javascript doesn't support multithreading - but isn't this multithreading? It runs the second statement before completing the first. Why would it ever do this?

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.