Problem with JavaScript is that it is single thread environment. Every thing we do in JavaScript is managed and calculated by single thread. Sometimes it happen that you have some more computation intensive task and your webpage performance may degrade(e.g. UI animation or transition performance). In this case, To achieve Parallelism, you can use Worker interface to spawn a new thread in background to do complicated calculation.

Worker thread can not directly communicate with Main thread, that means you can not directly change the content of any element in webpage(i.e. Inside Worker thread you can not run document.getElementById("demo").innerHTML = "demo";. You can not even alert from worker).

When to use Web Worker?

Creating new Web Worker

In case if your webpage have some code that is always running in the background like sorting algorithms, finding new position for animation, sine-cosine calculation etc.

You can create a new Web Worker using Worker() Constructor with Script location as argument.

var worker = new Worker("test_worker.js");

Setting Listener on Worker Thread

worker.addEventListener('message', function(e) { //Your action code goes here //received dataa will be in e.data alert(e.data); }, false);

You can setto receive message from Worker thread as following:

Third argument here is useCapture. You can Google it for more help. You can also set Listener as following:

worker.onmessage = function (e) { //Your action code goes here alert(e.data); }

You can use either of this way to set Listener on Worker

In "test_worker.js", you can set Listener to receiver message from Main Thread as following:

self.addEventListener('message', function(e) { //Your action code goes here i = i + 1; self.postMessage(i); }, false);

Same way you can also use following method:

var i = 0; self.onmessage = function (e) { //Your action code goes here i = i + 1; self.postMessage(i); }

Here, postMessage() method is used to send message from Worker thread to Main thread and vice versa.

You can terminate Worker Thread using terminate() method:

worker.terminate();

Combining all this together, you can write your Multithreaded code for your highly computation intensive task, Which in turn will improve performance of web application.

Liked What You Read? Take a Next Step. Share It (Click Below) !! Let Others Know.