Worker Thread / Web Workers in Angular / Javascript Applications

An Introduction to Web Workers and Threads:
Javascript usually execute in a single thread. Usually the single thread application works as a list of task where the browser works its way through this list executing each task one at a time. The problem with a single-threaded architecture is that if a particular task takes a long time to complete everything else is held up until that task finishes. This is known as blocking. So using this type of architecture will lead our application to be slow or even completely unresponsive, in the world of client-side applications.

So here comes the solution to this issue.. “Worker Thread / Web Thread”. Here using this architecture the browser can execute multiple tasks at once leading to towards multi-threaded architecture. Creating new thread for a huge task to complete, makes our browser to be faster and responsive.

Creating A Web Worker / Worker Thread:
First we need to create a javascript file containing all the code that we want for worker to execute.
Then create a new Worker object, passing in the path to the file that contains the code that your worker is to execute.

Once the worker is created, you can fire it up using the postMessage() function.

How to Communicate with a Web Worker:

To use worker we need to know to pass data between your main application and the web worker.
This can be done using “messages”. The “messages” can be just a string or javascript object.
To send some data from our main application to a web worker you call the “postMessage()” function on our worker object.

Inside your worker script you would setup an event listener for the message event.

Here the worker will send the message back to the application

When sending message back to the application we still use “postMessage()” but along with “self”
The final step is to setup an event listener back in the original application that will listen for messages that are sent by the worker.


Application (to worker):Worker
Working on Worker: Hello worker
Application (to console)==>> Working on Worker: Hello worker

Termination Of Worker:

Once you are done with a worker you can terminate it by calling the terminate() function on your worker object. To have a worker terminate itself you need to call the close() function on self.

Make sure to terminate them when they have finished executing their given task.

One thought on “Worker Thread / Web Workers in Angular / Javascript Applications”

Leave a Reply

Your email address will not be published. Required fields are marked *