Is there a way to create a parallel execution using javascript? [duplicate]

5

I wanted to know if there is a way to use parallelism in javascript . For those who come from the world of java or C this is a well known and used term, the known threads .

  

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

I've been thinking of a process that is running in standy-by as it can be done in lower level programming with while(1) for example, waiting for the iteration of some external process, consuming some web-service , while that this processing would not stop my application front-end .

I do not know if with an image I can make it clearer ...

Forexamplethefollowingcode:

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

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

If it crashes it locks any browser, in fact it only hangs the page where it was executed because of while(1) .... in my view, if it were possible to mount this in parallel processes, it would not crash.     

asked by anonymous 21.01.2017 / 14:30

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 content of the main thread through the onmessage event and will send it by the postMessage method.

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

Below is a complete example, to create a URL for the Worker, I am putting the script into 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 implement an implementation with Workers and I had a question, the answer given by @Gomiero can help you understand some factors: C # Parallel.ForEach equivalent in JavaScript

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

Even the following script might 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 , as I do not know what you're using on the server, I'll give you some options:

21.01.2017 / 15:21