Is there a way to create a parallel run using javascript?

Asked

Viewed 1,062 times

5

I was wondering if there’s a way to use parallelism in javascript. For those who come from the world of java or of C is a well-known and widely used term, known as threads.

Parallelism => is a program with the ability to divide tasks into small parts and run them in parallel.

I kept thinking about a process that was running on standy-by as well as can be done in the lowest level programming with while(1) for example, that awaits the iteration of some external process, consuming some web-service, as long as this processing did not stop my application front-end.

I don’t know if with an image I can make it clearer...

inserir a descrição da imagem aqui

For example the following code:

<imput id="a" type="text">
<script>
  (function() {
    x = a.value;
    while (1) {
      if (x === "string") {
        alert("entrou");
      }
    }
  )

  function teste() {
    alert("Sou uma função");
  }
</script>

If running hangs any browser, it actually hangs only the page on which it was executed because of the while(1).... in my view, if it were possible to mount this in parallel processes, I would not.

  • 2

    @bfavaretto gave an answer on that subject here. It’s already a bit enlightening =]

  • So @Lucascosta, hit by bfavaretto’s answer, my question is more about whether there is a way to create threads of parallel processes :) it’s a little different the concept of asynchronous with thread

1 answer

7


Yes, it is possible using Web Workers.

The code to be executed on a separate Thread must be in a separate file, it will receive the contents of the main thread through the event onmessage and will send by the method postMessage.

In the Main Thread you must create a Worker, this will have an event onmessage to receive messages and can send using the method postMessage.

Below is a complete example, to create a URL for Worker, I am mounting the script in memory.

var generateUrl = function (id) {
  var dom = document.getElementById(id);
  var blob = new Blob([dom.textContent], { type: dom.type });
  return URL.createObjectURL(blob);
}

var workerUrl = generateUrl("worker");
var worker = new Worker(workerUrl);
worker.onmessage = function (event) {
  alert(event.data);
}
worker.postMessage('Hello World!');
<script id="worker" type="text/task">
  onmessage = function (event) {  
    var reverse = event.data.split("").reverse().join("");
    postMessage(reverse);
  } 
</script>

Some time ago I tried to carry out an implementation with Workers and I got a doubt, the answer given by @Gomiero can help you understand some factors.: C# Parallel.Foreach Javascript equivalent

Finally, if you need to maintain a client-server communication to receive updates of new records, Webworker is not the way.

Even the following script may be a better option for you.:

var atualizarConteudo = function (response) {

}

var atualizar = function () {
  var httpRequest = new XMLHttpRequest();
  httpRequest.open("GET", url, true);
  httpRequest.addEventListener("onreadystatechange", function (event) {
    if (httpRequest.readyState == 4) {
      if (httpRequest.status == 200) {
        atualizarConteudo(httpRequest.response);
      }
      //adicionar um delay entre as requisições.
      window.setTimeout(function () {
        atualizar();
      }, 1000);          
    }
  })
  httpRequest.send();
}

Following this line of reasoning, your best option would be to use a WebSocket, since I don’t know what you’re using on the server, I’ll give you some options.:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.