myHotTake

Tag: non-blocking tasks

  • Unlocking Web Workers: How Do They Boost JavaScript Speed?

    If you enjoy this story about Web Workers and find it helpful, feel free to give it a like or share it with someone who might benefit!


    I’m the coach of a soccer team, and my job is to ensure that everything on the field runs smoothly. I’m like the main thread of a JavaScript application, responsible for handling all the tasks. But sometimes, the game gets intense, and I need extra players to tackle different parts of the field simultaneously. This is where Web Workers come into play.

    Think of Web Workers as specialized players who can focus on specific tasks independently without being distracted by everything else happening on the field. When I see that the opposing team is putting up a strong defense, I call in a Web Worker, like a skilled striker, to focus solely on breaking through the defense, while the rest of the team continues with the game plan.

    I pass a specific instruction, or message, to my striker Web Worker, like telling them to take the ball and aim for the goal. This striker doesn’t need to worry about what the goalkeeper or the defenders are doing—they just concentrate on their task. Meanwhile, I’m still coordinating the rest of the team, ensuring everything else runs smoothly.

    Once the striker has completed their task, they send a message back to me, the coach, letting me know the result—whether it’s a goal or a need for a different strategy. This exchange is seamless, allowing the game to continue without any unnecessary pauses or disruptions.

    By having these specialized players, or Web Workers, I can handle more complex plays and ensure our team performs at its best, without bottlenecks or lag. It’s all about having the right people focused on the right tasks, making the game flow effortlessly and efficiently.


    Here’s how I’d create a simple Web Worker:

    1. Creating a Web Worker

    First, I need to create a file for the worker script, say worker.js:

    // worker.js
    self.onmessage = function(e) {
        console.log('Message received from main script:', e.data);
        let result = e.data * 2; // A simple operation
        self.postMessage(result);
    }

    2. Using the Web Worker in the Main Script

    Next, in my main script file, I can create a Web Worker and communicate with it:

    // main.js
    if (window.Worker) {
        const myWorker = new Worker('worker.js');
    
        myWorker.postMessage(10); // Sending a message to the worker
        console.log('Message posted to worker');
    
        myWorker.onmessage = function(e) {
            console.log('Message received from worker:', e.data);
            // Handle the result from the worker
        };
    } else {
        console.log('Your browser doesn’t support web workers.');
    }

    Key Takeaways

    • Parallel Processing: Like having specialized soccer players, Web Workers enable parallel processing, allowing the main thread to continue executing other tasks without waiting for the worker’s task to complete.
    • Non-blocking: They help keep the UI responsive by offloading heavy computations to the background.
    • Message Passing: Communication between the main script and the worker is done via messages, ensuring data is passed back and forth seamlessly.