In this article, we’ll explore how Web Workers work, how to create them, and how to communicate between them and the main thread.
Note: This uses recursion so don’t try it with large numbers! We won’t go into details of optimising the factorial function here.
In this example, the
onmessage function is called whenever a message is received from the main thread. The message contains the number we want to calculate the factorial for. The factorial function calculates the factorial of a number recursively.
To create a Web Worker from this file, we can use the Worker constructor:
This creates a new Web Worker from the
worker.js file. We can then send messages to the worker using the postMessage method:
This sends a message containing the number 5 to the worker. The worker will then calculate the factorial of 5 and send the result back to the main thread using the postMessage method:
This logs the result of the calculation to the console.
Web Workers communicate with the main thread using the postMessage method and the
onmessage event. The
postMessage method sends a message to the other thread, while the
onmessage event is called whenever a message is received.
Let’s modify our previous example to calculate the factorial of multiple numbers:
In this example, we create a new Web Worker from the
worker.js file. We then send messages to the worker containing an object with the number we want to calculate the factorial for. The worker calculates the factorial and sends the result back to the main thread in an object containing the original number and the result.
Partytown ↗️ is one of the library that allows you to create multi-threaded web applications using Web Workers.
Web Workers are a great tool for improving the performance of web applications, especially when dealing with large amounts of data. By offloading heavy computations to separate threads, Web Workers can free up the main thread to handle user input and other tasks, resulting in a smoother and more responsive user experience.
If you’re looking to improve the performance of your web application, give Web Workers a try. With a little bit of effort, you can create multi-threaded applications that are fast, responsive, and a joy to use.