How does web workers for heavy tasks work internally in JavaScript?

Web Workers in JavaScript allow you to run scripts in background threads, separate from the main execution thread of a web application. This enables you to perform heavy tasks without blocking the user interface, resulting in a smoother user experience.

Internally, when a web worker is created, a new instance of the JavaScript engine is instantiated, allowing it to run concurrently with the main thread. Communication between the main thread and the web worker is achieved through a messaging system, where data is sent back and forth using the postMessage method. This communication uses a structured clone algorithm for transferring data, ensuring that the data remains consistent and isolated between the worker and the main thread.

Here’s an example of how to create and use a web worker:


        // main.js
        const worker = new Worker('worker.js'); // Create a new worker

        worker.onmessage = function(event) {
            console.log('Message from worker:', event.data);
        };

        worker.postMessage('Hello, Worker!'); // Send message to worker

        // worker.js
        onmessage = function(event) {
            console.log('Message from main script:', event.data);
            postMessage('Hello, Main Script!'); // Send a message back to the main script
        };
    

Web Workers JavaScript Background Threads Heavy Tasks User Interface