Vinay Kumar

Introduction to web workers

Web worker is a web API which allows the execution of Javascript file in a separate background thread. By leveraging web worker, you can offload any time consuming process from the main thread of the web application there by maintaining operational UI screen, click events etc. A new instance of worker can be initiated by using the below command

new Worker('path to js file')

To send any data to the script worker file we can make use of postMessage() method and to receive data from the worker we can make use of onmessage() method. You can pass string, array, object etc as argument to the postMessage() method.

// index.js
let worker = new Worker('path to js script file');
worker.postMessage({message: 'I am from main thread'});
worker.onmessage = function(response){
   const data = response.data;
   worker.terminate();
}

Any message received by the worker script will be available in the onmessage event and passed values will be available in data attribute. We can send response back to the callee script by making use of postMessage() method.

// worker-file.js
onmessage = function(event){
     let message = event.data; //I am from main thread
     postMessage();
 }

To get a practical sense, let's create a sample program for computing summation of consecutive n numbers with and without web workers.

After running the above code in web server of your choice, try moving the mouse pointer after clicking "Without web worker" button and once again try moving the mouse pointer after clicking "With web worker" button. If you are still not convinced then repeat the above steps after adding 2 more zero to the limit variable present in index.js file.

For more info on web worker do have a look at the mozilla docs.