Is JavaScript single threaded? If not, how do I get synchronized access to shared data?

pdc picture pdc · Oct 2, 2008 · Viewed 8.6k times · Source

I have a web page with DIVs with a mouseover handler that is intended to show a pop-up information bubble. I don't want more than one info bubble to be visible at a time. But when the user moves the mouse rapidly over two items, I sometimes get two bubbles. This should not happen, because the code for showing a pop-up cancels the previous pop-up.

If this were a multi-threaded system then the problem would be obvious: there are two threads trying to show a pop-up, and they both cancel existing pop-ups then pop up their own pop-ups. But I assumed JavaScript is always run single-threaded, which would prevent this. Am I wrong? Are event handlers running asynchronously, in which case I need synchronized access to shared data, or should I instead be looking for bugs in the library code for cancelling pop-ups?

Edited to add:

  • The library in question is SIMILE Timeline and its Ajax library;
  • The event handler does call SimileAjax.DOM.cancelEvent(domEvt), which I assume based on the name cancels the bubbling of events;
  • Just to make thing s more complicated, what I am actually doing is starting a timeout that if not cancelled by a moustout shows the pop-up, this being intended to prevent pop-ups flickering annoyingly but annoyingly having the reverse effect.

I'll have another poke at it and see if I can work out where I am going wrong. :-)

Answer

pkaeding picture pkaeding · Oct 2, 2008

Yes, Javascript is single-threaded. Even with browsers like Google Chrome, there is one thread per tab.

Without knowing how you are trying to cancel one pop-up from another, it's hard to say what is the cause of your problem.

If your DIVs are nested within one another, you may have an event propagation issue.