Tuesday, December 17, 2013

Threading to JavaScript 1

JavaScript is a single-threaded environment. Simply if you wants run multiple scripts at the same time you cant achieve that requirement with JavaScript. Think about the scenario in a web site you wants to retrieve data through AJAX, needs to do manipulation in UI and DOM at the same time. But you can do this because of script execution happens within a single thread. So in currently what you do normally achieve this kind of goal. You use techniques like setTimeout(), setInterval(), XMLHttpRequest, and event handlers. But in HTML5 gives to you better option than these workarounds. That is Web Worker.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. perfect for keeping your UI refresh, performant, and responsive for users. There are two types of web workers, Dedicated Workers and Shared Workers. In this article discuss about Dedicated web worker.

Let's do small demo about web worker. Create HTML content like below with two buttons. Those two buttons bind with 'onClick' event.

Web worker demo

Create script like below with two onClick events. First of all check whether browser support web worker. After check Worker object create or not. If it not create new object. If the web worker file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. The worker will not begin until the file has completely downloaded and executed. If file not exists returns an 404, the worker will fail silently. Communication between a work and its parent page is done using an event model and the postMessage() method.


Following script shows the content of doWebWorker.js file. In this javascript file capture message from main page send data back to main page. And also worker terminate operation contain in this separate script file.
var message;
that = this;
self.addEventListener('message', function (e) {  
 //basic demo
 message = e.data;
 that.sendMessage(message);
}, false);

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

When click Start Worker button send message to the web worker and eventlistener of web worker catch it send back to the main page. When click Stop Worker button terminate web worker.



No comments :

Post a Comment