2

Yes I'm aware that asking for a formal memory model in Javascript is a hopeless undertaking, so I'm settling for "All browsers follow these rules" or something.

My problem is the following: I have to send events in a defined interval to a server, but events may be added to my array while doing so, i.e.:

function storeEvent(event) {
    // may be called at any time
    storedEvents.push(event);
}

function broadcastEvents() {
    if (storedEvents.length !== 0) {
        var eventString = JSON.stringify(storedEvents);
        storedEvents = [];
        // send eventString to server
    }
    window.setTimeout(broadcastEvents, BROADCAST_TIMER);
}

There's an obvious race condition in there and not even think of the missing memory barriers.

What to do? Really missing the Java memory model here..

Voo
  • 29,040
  • 11
  • 82
  • 156
  • 1
    See [this post](http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649) for a brief description of how javascript's event queue works and why this isn't a race condition. – jfriend00 Nov 27 '11 at 05:12
  • @jfriend00 Thanks - so it's basically the usual message pumping implementation without reentrancy. Good to know even if it doesn't matter apart from "it's single threaded" :) – Voo Nov 27 '11 at 13:59
  • yeah that's a good way to describe it. – jfriend00 Nov 27 '11 at 17:53

1 Answers1

4

There isn't any race condition.

All JavaScript code in the browser is single-threaded.

The setTimeout callback will run on the UI thread while it isn't doing anything else.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • So all user events, setTimeouts(), broadcasts from the comet server,.. are all pushed onto a message queue that is then handled by one thread? Not the most efficient thing, but I assume simple enough. Can I read up on that somewhere? – Voo Nov 27 '11 at 03:12
  • @Voo: Correct. HTML5 web workers allow you to use background threads. Read up on what? – SLaks Nov 27 '11 at 03:31
  • Before asking I looked around a bit and well the whole ECMA spec does not once mentions "thread" anywhere - so I was just wondering whether you knew of some source for the "actual implementation" in browsers - only out of curiosity and on second glance not likely to exist. Looked at the MDN documentation of Web workers - interesting, thanks (avoiding the whole shared memory mess by message parsing is certainly the best solution). – Voo Nov 27 '11 at 03:40