HTML5 Web Worker - Threading in JavaScript

I recently used this new technology in a TV app. so I thought I should share it .

So we all know that a web page runs on a single thread. It means if you are doing any processing in JavaScript, for that time being your page will become unresponsive until script is done . With web workers you can run that part of JavaScript independently in the background, on a separate thread.

The communication between your main script and worker is via events . Lets get down and dirty and look at some example code.

Your main code will look like this. Lets call it main.js.




if(typeof(Worker) != undefined){ //checking browser support

//Creating new Worker. You have to give it the path to worker file. 
//This file doesn't need to be included in HTML 
var myWorker = new Worker('myWorker.js'); 

//Listening for the response from Worker 
myWorker.addEventListener('message', function(event){ 
  
console.log(event.data); //Calculated result. This will print 300.

 });

 //Sending data to Worker wrapped in an object.
 myWorker.postMessage({num1: 100, num2: 200}); 
}



Now lets have a look at Worker script. Lets call this myWorker.js.




//This will listen for any event thrown at it.
self.addEventListener('message', function(event){ 
 
var num1 = event.data.num1;
 var num2 = event.data.num2;
 var result = num1 + num2;

 postMessage(result); //responding back with the result
 
}, false);


I hope you’ll give it a go and this new feature in HTML will make web programming more fun and a good experience for end user.

Re: HTML5 Web Worker - Threading in JavaScript

awesome man!