Intro
No it is not, but it can be setup to run code in paralel. And this is confusing, because Java is also single threaded if Threads are not used, isn't it?
I think that devs who have been using single-threaded JS for the whole career become deeply offended when somebody inaccurately mentions multithreading.
I have browsed a little bit on this subject and everybody who mentions JS is single-threaded omits to specify their source - always.
I have tried to find this proof in Ecma-international standard, with no success. Maybe I am looking in the wrong place? However, here is the formulation from Mozilla developers:
And mozilla source is recomended from Javascript-manual. So there are sources that discuss Threads in JS. And almost all sources mention Web Workers. This is what this article is about.
Web Workers
It took me a while to understand how Web Workers work. How they interact with main thread, and how main thread interacts with Web Workers. I need to confess, I am not a JS developer, however I create JS scripts occasionally.
So what is a web worker - it is just a Worker instance in JS that loads a script and runs it. Additionally it has an API that allows communication between main and worker threads.
To demonstrate how they work I imagined the following scenario, I want to display content on a web page that is generated from different Web Workers in parallel, so that it is clear from the content which Worker generated it.
Basically I want to have a button "Start worker" and whenever I press it a new Worker is created and added to the Pool(map) of existing workers. When I press "Stop workers" all workers are closed and content is cleared.
When worker starts, it loads a Job, so to speak, from workers.js. It starts processing when called with "Start" command and sends a message to the main thread each 500 milliseconds. When it receives "Stop" it terminates.
A Worker is started from main thread. Each time "Start worker" button is pressed a new Worker is created by loading worker.js and receiving a startup message composed of [, "Start"].
All workers are closed by sending termination command to each worker [, "Stop"], Worker name is not yet used while closing, however it may be useful to stop a particular worker, in the future.
The problem
Current browsers have a security CORS policy and don't allow for a script to be loaded from local machine, only from a Web Server. But I want this application to work without additional setup. Thus the solution I found was to load the worker.js file in an input field and from there to use it to instantiate Workers.
Demonstration
Open index.html in browser, press Start worker button a couple of times and observe how content is being generated
Sources
Code is available in Github
References
Author Of article : Mircea Sirghi Read full article