Web workers in JavaScript for multi-threading

Updated

In many situations, having more than one thread running in a program is beneficial. We really have to start thinking about how our program can do multiple things simultaneously, and architect our program with features designed to allow pieces of the program to be handled asynchronously. The introduction of Web Workers as a part HTML5 API helped developers in achieving this which wouldn’t have been possible otherwise.

Introduction to Web Workers :

Generally JavaScript runs in a single thread meaning that it runs on a single window. Browsers decided what JavaScript should be allowed to do and what it it should not be allowed to do. One of the big things that was not allowed was any form of threading for quite some time. This was due to performance and security reasons. But, this became a disadvantage since many developers would have wanted to do advanced processes. Threads help in making use of the processing power that’s available on the client side. So this was the case until W3C decided to introduce the concept of Web Workers into HTML5. But this kind of threading is kind of a “simulated” one meaning that the full power of threading that are available on applications based on Java and C++ are not going to applicable here. But it does work out for some scenarios.

What are Web Workers :

In simple words, Web Worker is nothing but JavaScript running in the background of the main Browser window. The threading system here is very simple. It is implemented through a messaging system wherein the JavaScript running on the Browser window communicates with the worker running in the Background using messages and once the worker is done processing the required task it replies back to the main UI window with a message.

A page and a worker send messages to each other with postMessage and onmessage, and the console prints Hello.

So when are Web Workers particularly useful? The answer is pretty simple. Whenever there is a large amount of computing required, Web Workers come into the picture. Some examples to quote are Cryptography, sorting of large arrays, Parallel processing. From these examples it is easy to see where Web Workers could be of a big help. So what will happen if these processes run on the main UI thread? The answer is simple. They will of course run but these operations will slow down your UI and your site or app may ultimately crash.

A Simple Demonstration of Web Workers in action :

Main Script (script in the HTML file) :

var w = new Worker('worker.js');
/*Calling the Worker constructor and passing worker.js as the parameter since worker.js contains the worker script (its assumed here that both the HTML file and the worker.js file are in the same folder)*/
w.onmessage=function(e){

console.log('Message from the worker is: '+e.data);

};

/*onmessage event handler is attached to the worker instance so that the main script responds to any messages posted by the worker script, e.data contains the message from the worker script. Output in the console in this case would be "Message from the worker is: Hello!!" */

w.postMessage('Hello!!'); //sending message to the worker script

Worker script (script in the “worker.js” file) :

onmessage=function(e){

postMessage(e.data);

} ;

/*This function responds to any messages posted by the Main script and e.data contains the message from the main script and postMessage sends data to the Main script. In this case it sends "Hello!!" to the main script that it received from the main script.*/

Limitations Of Web Workers :

As mentioned earlier, the Web Workers run in the background and not in the main UI thread. It’s because of this fact that Web Workers have some restrictions. One such restriction is that it cannot access the Document Object Model(DOM) that runs on the main UI thread and hence it cannot render or read the DOM. It also leads to the conclusion that Workers can’t access the local or the global variables on the main script. Access to the window object is somewhat restricted. Thus, Workers help us only in processing any data. The processed data should be sent to the main UI thread an any UI rendering should take place through the main script/UI thread.

Conclusion :

Multi threading in JavaScript with the help of Workers has brought new possabilties. We can handle any complex process or asynchronous tasks such as XML HTTP Requests in the background while any other process can run in the main UI thread until the Worker process completes. It has also opened the door to the world of parallel processing in JavaScript although they have their own limitations as we saw earlier.

Comment
Next tutorial
Mithlesh Upadhyay Published 25 Nov 2026 · 4 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials

  • Find common elements of two arrays in JavaScript

    The objective is to find the common elements of the arrays, which means if there are two arrays given as A1 = [5, 6, 2, 3, 4] A2…

    4 min read
  • Sort an array of objects by a field in PHP

    Write a program in Php to sort an array of objects by any object field. Here, we will take a array of student with fields as Id, Name,…

    2 min read
  • URLSearchParams.append() method in Node.js

    The urlSearchParams.append() is an inbuilt application programming interface of class URLSearchParams with in url module which is used to append the associate argument of name to value in…

    2 min read
  • Readable, writable and duplex streams in Node.js

    A stream in Node is simply a sequence of bytes. A stream contains a buffer of bytes, and this buffer has a zero or greater length. In Node,…

    3 min read
  • What are the advantages of the Internet?

    Here in this article we will discuss about the various ways through which the net is headed up in the world. Employment Opportunities: Employment opportunities will get open…

    4 min read
  • Strict mode in JavaScript

    For a long time, JavaScript had no compatibility issues because in every new version release old functionality were not changing. But it was not good as if there…

    2 min read