SitePoint Sponsor

User Tag List

Results 1 to 12 of 12

Threaded View

  1. #1
    ********* Ornithologist AtomicPenguin's Avatar
    Join Date
    May 2002
    Location
    Vancouver, BC
    Posts
    459
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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".

    Code:
    document.getElementById("myid").innerHTML = mystr.replace(/some complicated regexp/g, str);
    document.getElementById("myinputfield").value = "something";
    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.

    Any information you could provide would be very welcome!
    Last edited by AtomicPenguin; May 14, 2007 at 14:23.
    A.P.

    generatedata.com - free JS/PHP/MySQL random test data generator.
    Form Tools - free PHP/MySQL form processor.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •