skip to Main Content

In JavaScript if I need a for loop multithreaded, what is the simplest possible way to do this (browser or node)?

So that

For x in 5: print (x)

Would run each for loop pass in parrelell. It doesn’t matter if they happen in order.

Is this possible to do simply?
Is this even a thing?

2

Answers


  1. JavaScript runs in a single line, one thing at a time. If you want to do a "for loop" in multiple lines at once, you can use something called Web Workers in browsers or worker_threads in Node.js.

    Login or Signup to reply.
  2. JavaScript is single-threaded due to its event-driven and non-blocking I/O nature. You can’t achieve true multi-threading directly.
    Though, you can achieve concurrent execution using technique like Web Workers in the browser.
    This will not give you true multi-threading, but can help you run code concurrently in separate threads.

    Here’s an example of how you can achieve that using Web Workers in a browser environment:

    Script in HTML:

    <body>
      <script>
        //create multiple web workers
        const numWorkers = 5;
        const workers = [];
    
        for (let i = 0; i < numWorkers; i++) {
            const worker = new Worker('worker.js');
            workers.push(worker);
    
            worker.postMessage(i); //send data to the worker
        }
    
        //listen to messages from workers
        workers.forEach((worker, index) => {
            worker.onmessage = (event) => {
                console.log(`Worker ${index} returned: ${event.data}`);
            };
        });
      </script>
    </body>
    

    Create the worker script that does the work:

    //worker.js
    self.onmessage = function(event) {
      let x = event.data;
    
      //perform some work here
      let result = `Result for ${x}`;
    
      //send the result back to the main thread
      self.postMessage(result);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search