WebWorker and Async - What's the difference and when to use it?

4

I'm specifically studying a WebWorker implementation, and I did not quite understand the difference between WebWorker and Async in JavaScript, whereas WebWorker gives me an asynchronous solution with a better (or better) code organization.

    
asked by anonymous 27.04.2017 / 16:08

1 answer

4

Both are somewhat similar.

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

Webworkers are also part of this list, even though they are not in 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 poor utilization of multi-core processor hardware, Webworkers has appeared for parallel programming. Memory access is limited to data that is being exchanged with them. They run on separate threads and the UI is available for other activities.

Workers can not access the DOM to read or modify the HTML document. Also, they can not access any global variables or JavaScript functions within the main page. Access to some objects, including the window, the document are restricted.

Illustration:

Note:IfyouwanttogodeeperintoWebWorkers,Irecommendreadingthisarticle:

  • Introduction to Web Workers: How to bring sequencing to JavaScript .

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

In the W3C documentation, you have an example 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" should be in a separate file, because they are   executed in isolated sequence.

demo_workers.js

var i = 0;

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

timedCount();

Source:

28.04.2017 / 15:37