a blog for those who code

Friday 7 October 2016

Getting Started with Web Workers in HTML5 - Multi Threading in JavaScript

In this post we will be discussing about web workers in HTML5. Web Workers allows us to write a multi-threaded JavaScript applications. As we all know that JavaScript is a single-threaded environment, meaning multiple scripts cannot run at the same time, thus HTML5 Web Workers will allow us to run multiple scripts together (bringing multi-threading to JavaScript).


Advantage of using HTML5 Web Worker are to build more responsive applications as well as able to leverage today's multi-core CPUs. Simply a web worker can be defined as a JavaScript code that runs in the background of the web page. It doesn't interrupt the user and the web page remain responsive because they are running tasks in the background.

Types of Web Workers


1. Dedicated workers - Are linked to creator and cannot be shared among others
2. Shared workers - Are named workers, can be shared among the workers of the same origin

Dedicated workers are the workers which are dedicated to the owner which creates them. These workers can message back and forth only to the owner but not to the host process whereas shares workers can be shared among multiple owners thus can message back and forth to the multiple threads. In this post we will be discussing about only Dedicated Workers.

The best thing about HTML5 Web Workers are its support. It is supported in almost all the web browsers as shown below:

PC : http://caniuse.com/#search=Web%20Workers

The limitation of the Web Worker is that it cannot access the DOM as they operate independently of the main browser UI thread, so they can't read or modify the HTML document. It can access all the objects that are not directly related to the Document or main UI thread.


What is the use of Web Worker


Worker can run the long running loop to do all the computation and can send and receive messages from the owner who has created it (can be a UI thread) in the case of Dedicated Workers. It can call JavaScript functions like setTimer, setInterval, eval, parseInt etc. It can use XMLHttpRequest and WebSockets to communicate with the HTTP servers. It can use synchronous and asynchronous file APIs and indexed DB APIs. A worker can also create a new worker.

How to Create Web Worker


Since Web Workers run in an isolated thread, the code which they will run needs to be written in a separate file. You can create a new Worker object as shown below :

var worker = new Worker('myWorker.js');

// myWorker.js
var result = 5 * 10;
postMessage(result); // Sending message to the creater

How to Communicate With the Web Worker


In the below code we have created a mechanism where we will be passing message to the worker and get the message back. Message can be anything, it can be a object, a string, a value etc. So from the main method we have created a worker and added a listener to it. Then we are passing values to our worker to do the computation. Inside our worker we should have a listener to get the values from the owner, then we are extracting the values and sending back the result using postMessage function. We can terminate the worker using the command worker.terminate().

// main thread
var worker = new Worker('myWorker.js');
worker.addEventListener("message", onMessage, false);
worker.postMessage({value1: 5, value2: 10});

function onMessage(e) {
  alert(e.data);
}

worker.terminate();

// myWorker.js
addEventListener("message", onMessage, false);

function onMessage (e) {
  var v1 = e.data.value1;
  var v2 = e.data.value2;
  var result = v1 * v2;
  postMessage(result);
}

How to Load Extrnal Scripts inside Web Worker


One more useful thing in Worker is the ability to import other javascript files into a Worker. You can load external script files or libraries into a worker with the importScripts function. This method takes zero or more strings representing the filesnames for the resources to import as shown below :

importScripts('a.js', 'b.js');

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment