Web Workers in Javascript

Posted By : Ankit Uniyal | 12-Jan-2017

In this blog, we will discuss the Web Workers specification and how it can be useful for us.

Web Workers provides a mechanism to run a script in background thread and can perform taks without interference of user interface.It basically lives in a self contained execution environment and it has not access of DOM and Window object and can communicate with main execution thread.

To create a new worker, use the Worker constructor with passing a URL on which worker will work.

var loaderObject = new Worker("newUtil/file.js");

You can also specify a relative URL and the same will resolve relative to the URL of the document that contains script and for absolute URL, it should have same origin.

After having Worker object, you can send date with postMessage() function.

loaderObject.postMessage("newFile.txt");

With onMessage event handler, you can receive messages from a Worker by listening to onMessage event handler.

worker.onmessage = function(e) {

var textMessage = e.data; // Get message from event

console.log("Contents are: " + textMessage); // Do something with it

}

How to terminate a Worker :

For terminating a worker from main thread then you need to calling the terminate method of Worker's object.

worker.terminate();

 

Handling Errors :

When a worker throws an exception then its onerror event handler is called :

myWorker.onerror = function(err) {

console.log("error occurs");

}

Thanks

About Author

Author Image
Ankit Uniyal

Ankit has knowledge in Javascript, NodeJS, AngularJS and MongoDB also have experience in using AWS Services.

Request for Proposal

Name is required

Comment is required

Sending message..