Web worker

There is only one thread for Javascript in browsers. It is enough for the browser to deal with the UI actions. However, the CPU became multi-thread and the Javascript can do much more work in browser. Web workers are developed to utilize multi-core CPU more effectively. The simplest use of workers is for performing a computationally expensive task without interrupting the user interface. Once a web worker is created, it will run continuously. Web workers are relatively heavy-weight and are not intended to be used in large numbers. They are expected to be long-lived, with a high start-up performance cost and a high per-instance memory cost.

As web workers work run outside the content of an HTML document’s scripts, they don’t have access to the DOM, they can facilitate concurrent execution of different JavaScripts programs. They can’t execute alert() and confirm() method but consone.log() is allowed to debug the program.

Main Thread

A web worker is created by the Worker() function. It runs a different Javascript.

var w=new Worker('work.js');

Then use w.postMessage(obj) method to send data to the worker,

var msg={a:123,b:0.3,c:'abc'};
w.postMessage(msg)

Finally, create a function to handle the data from the worker,

w.onmessage=function(e){
console.log(e.data);
}

Worker Thread

The worker thread called itself as self. More script can be loaded in the worker thread through importScripts() method(file). The path of the file is relative to the script file of the thread.

importScripts('math.js');

Then use onmessage() method to receive the data from the main thread.

self.onmessage=function(e){
console.log(e.data);
};

Finally, use postMessage() method to send the result to the main thread.

self.postMessage(msg);

Leave a Comment