Search code examples
javascriptweb-worker

How can I recieve messages from Web Workers when they have the same name?


I am currently learning Web Workers in JavaScript, and therefore, making a script says something 8 times, every thread does 1.

So to make it, I use this code:

main.js

for (let workersAmount = 0; workersAmount < 4; workersAmount++)
{
    var socketWorker = new Worker("worker.js");
}

socketWorker.onmessage = function(event)
{
    console.log(event.data);
}

worker.js:

postMessage("Why can't it just work!")

And this is the result (this is my first post here so I can't embed): image

As you can see, it only shows the text 1 time, while there are 4 workers. Which (I think) is because is replace the variable "socketWorker" everytime, but still keeps the old worker.js

So, does anyone know how to fix this? Thanks in advance for you help!


Solution

  • They don't have the same name. They don't have names at all.

    The socketWorker variable has a name. It also has a value.

    First it has the value that is a reference to the first worker. Then you immediately overwrite it with the value that is a reference the second worker. And so on.

    When you overwrite the first reference you no longer have that reference.

    You have thrown it away.

    You can't get it back.

    By the time you get to the line socketWorker.onmessage = function(event), you've only got the last reference you stored in socketWorker available to you.


    Assign a value to the onmessage property inside the for loop, before you overwrite the value of socketWorker.

    If you need to keep a reference to each of your workers around for the future, then push them into an array instead of using a single variable which you keep overwriting.