2

I wonder if there is a way to synchronize objects/methods in JavaScript in a similar way that you can do it in Java. I am developing an interface for the new WebSocket in html5 and need a way to match outgoing requests with incoming responses. Therefore I'm saving the requests (with a unique id) in an array on the client side and then I iterate through the array when I receive a response looking for the matching request.

A problem that might occur on the client side is if I have multiple timers that are making requests to the server independently of each other. If a the request function is inserting a "request-reference" into the array at the same time as the respond-listener is iterating through the array it's bound to break!

So how do I solve this problem? My initial thoughts was to simply synchronize the array as one could have done in Java (putting a lock on the object and force the other functions to wait) but I have found no syntax of how I would do this in JavaScript.

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
Snail
  • 467
  • 2
  • 7
  • 20

1 Answers1

3

Javascript runs in a single thread in the browser, so there is no need to synchronize.

See here for details. See this SO question and answers as well (Why doesn’t JavaScript support multithreading?).

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 1
    unless you use workers : see https://developer.mozilla.org/en/Using_web_workers but even then you have to work really hard to cause problems in your code – Redlab Jun 30 '10 at 08:27