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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankit Uniyal
Ankit has knowledge in Javascript, NodeJS, AngularJS and MongoDB also have experience in using AWS Services.