Webworker and Async - What is the difference and when to use it?

Asked

Viewed 163 times

4

I am studying specifically an implementation of Webworker, and did not understand very well the difference between Webworker and Async in Javascript, whereas Webworker gives me an asynchronous solution with a better (in my view) code organization.

  • At the moment I have no time to post a reply here @Bruno, but I started studying for this link and found it very good, worth checking. No more very interesting subject +1

  • Marconi, this link is interesting. I had already read it. However it does not clarify me well about the question itself.

  • Bruno I tried to explain in the best possible way, in case you still have any doubt add a comment to my reply. I’m trying to improve the answer.

1 answer

4


Both are somewhat similar.

Asynchronous functions are only possible when used with one of the following options:

Webworkers are also part of this list, even though they do not belong to the same category.

The main difference between all of them is access to resources. Using XMLHttpRequest you exchange data between client and server asynchronously using the same wire.

Due to the misuse of multi-core processor hardware came the Webworkers for parallel programming. Access to memory is limited to the data being exchanged with it. They run in separate segments and the user interface is available for other activities.

Workers cannot access the DOM to read or modify the HTML document. In addition, they cannot access any global variables or Javascript functions within the main page. Access to some objects, including the window, the document are restricted.

Illustration:

inserir a descrição da imagem aqui

Note: If you want to go deeper into Webworkers, I recommend reading this article:

The article has a very self-explanatory step-by-step how to create an asynchronous request with Webworkers.

In the W3C documentation, you have an example of a counter.

Javascript

var w;

function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
    }
}

function stopWorker() { 
    w.terminate();
    w = undefined;
}

The file "demo_workers.js" must be in a separate file, because they are performed in isolated sequence.

demo_workers.js

var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();

inserir a descrição da imagem aqui

Source:

Browser other questions tagged

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