Wednesday, January 15, 2014

Threading to JavaScript 2

The previous post explained about basics of web worker. In this post going to describe a small application created using web worker. In this demo shows add two numbers using web worker. Following HTML shows two inputs.

Web worker demo

Add numbers
Following JavaScript code reside in main page. This code start web worker and attach with event handlers.


JavaScript code snippet of doWebWorker.js,
var message;
that = this;
self.addEventListener('message', function (e) { 
 
 var sum = parseInt(e.data[0]) + parseInt(e.data[1]);
 var workerResult = 'Result: ' + sum;
 that.sendMessage(workerResult);
}, false);

function sendMessage(message)
{
 self.postMessage(message);
}

Following image shows the end result.