views:

119

answers:

1

Javascript does not have visible threads (yet -- Worker Threads are coming, see more info in http://stackoverflow.com/questions/30036/javascript-and-threads).

However, it does seem to have multiple execution contexts that appear to exist simultaneously -- independent, when you have multiple Firefox Windows, and multiple Firefox/IE tabs.

When you have multiple iframes on a page, each has its own execution context, but they have shared data. If two iframes are on the same domain, they can access each other's DOM and call each other's functions. Nevertheless, I couldn't find a on Google a description of the scheduling model, i.e. whether it is:

  • parallel/preemptive, in which case -- can you temporarily suspend? any form of mutual exclusion?
  • cooperative, in which case -- how does one yield to another context?
  • non-overlapping -- i.e., an event handler in the main frame must return before an event handler in the iframe may be invoked (And vice versa)?

So the question is:

  • Is there a guaranteed context switching model?
  • If not, what are the prevailing context switching models?
    • It seems Firefox and IE have a non-overlapping schedule between same-tab contexts, and cooperatively between different tabs/windows in the same process - but I'm not sure.
    • Chrome uses the system scheduler for different tabs (may use multiple cores, which is in the parallel/preemptive group, but I don't know what it uses for multiple frames in the same tab.
    • I have no idea about Safari or Opera.

Thanks!

+4  A: 

In Firefox, all the JavaScript in web pages runs on the main thread, so it is all serialized. Each frame will have its own JSContext, and each method is executed to completion. There is no preemption.

sdwilsh
(You know that, but for completeness: that's Firefox 3.5. As browsers become multiprocess, as Chrome already is and Firefox will be several versions later, unrelated tabs will probably run independently, while (at least for now) for "related" tabs the browser developers try to preserve the "run to completion" semantics.)
Nickolay
Sure, but Firefox doesn't do that yet, and won't at least until Firefox 4.0 ;)
sdwilsh
Separate tabs are on separate processes, no problems there. Iframes/frames within one tab still share the same thread. Js developers can still breathe easily and not worry about concurrency.
Juan Mendes