Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/web browser threading model

If I have javascript code running which for example performs some action on a timer and this code is embedded in web pages in tab 1 and tab 2 of a web browser, then could the client code run concurrently? Or is javascript client code always run in only a single browser thread?

Alternatively, if there is a frameset with a parent and child frames, then could javascript code run concurrently in this situation?

Is there a standard specified model or is it browser dependent?

My main target environment is IE9 so would be interested to know what happens there.

EDIT I am not looking for threading support or how to do threading in javascript. I personally don't see the need. It also makes life more complicated. I just want to know if I need to worry about it, and if so on which browsers.

like image 349
Angus Comber Avatar asked Mar 24 '13 11:03

Angus Comber


1 Answers

For a single JavaScript "object space" (a single page in a browser or an interpreter instance in node.js) there is at most one thread running. In fact speaking about threads in the context of JavaScript is not meaningful. The JS execution model is event-loop and callback based.

Different frames can never run concurrently because they can access the DOM (and by extension arbitrary objects) of each other. This would make threading unsafe.

With web workers there is no direct access to any data structure across the worker boundary so threading is not observable and can safely occur. The only communication here is through message passing.

like image 60
usr Avatar answered Oct 12 '22 23:10

usr