What is the difference between setInterval / setTimeout and Web Workers?

10

I was taking a look at some HTML5 features and came across these WebWorkers whose definition is:

  

When executing scripts in an HTML page, the page becomes unresponsive   until the script is finished. A web worker is a JavaScript that runs   in the background, independently of other scripts, without affecting   the performance of the page. You can continue to do whatever you want:   clicking, selecting things, etc., while the web worker runs in the   background.

Well, I could not distinguish very well the difference between this and setInterval and setTimeout . As far as I know, these two dispute the JS thread, allowing the time programmed to run late or something, and if it has a very low execution interval, can greatly affect page performance, right?

Then I looked at the example that W3S has in your site and here I come across it:

Index                   

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>

<p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p>

<script>
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;
}
</script>

</body>
</html>

demo_workers.js

var i=0;

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

timedCount();

Within this web workers, it has a setTimeout , which every 500ms sends to the page the update of the I value. So why not directly use setTimeout ? That does not make sense to me. Can anyone give a light, a jedi council?

Thank you.

    
asked by anonymous 01.02.2016 / 18:44

2 answers

6

The setInterval

The setInterval is an asynchronous loop within the current javascript process, ie it runs on the same layer as the larger process even though it does not need to wait, however if there are too many setInterval or callback of setInterval is very time consuming it will anyway hang browser (or tab, there are browsers like Chrome and Firefox Developer Edition that use multi-process).

The setInterval is repeated infinitely at each defined interval, unless you use clearInterval to stop it.

O setTimeout

This is almost identical to setInterval and also runs on the same layer as the current browser or tab process, the difference is that it only fires once and clearTimeout does not end replicates only, it can end a timeout in the middle of the path.

The Web Worker

The Web Worker runs on an isolated layer that is more like a% true%, so much so that can not control or access DOM elements directly from Worker because are different layers, it is necessary to work with signals (similar to the idea of Forms in C ++ for example) it is as if the file Thread called in Worker was in a separate browser, then with .js you send answers and with postMessage you capture, from both sides.

Exemplifying:

  • To send a message from a page called worker.addEventListener('message', ...); to foo.html you will have to use baz.js ( worker.postMessage is the name of a sample variable) and for it to get this message worker will have to use baz.js ( self.addEventListener('message', ...); is to refer to itself).

  • For self send a message to baz.js it will have to use foo.html and self.postMessage will have to have an event like foo.html .

Also note that worker.addEventListener('message', ...); is not supported by some older browsers.

Summarizing

With Web Worker / setTimeout you can interact directly with the current page but there may still be some locking problems, but in most cases they are useful, basically for even ranges.

You should use setInterval almost to run long, usually synchronous processes that easily freeze a page.

Answering the question

Worker within setTimeout was just to simulate a long process, does not mean that it's something real, it's to understand how Worker works, you could have created a loop inside% giant% in Worker which would have the same effect, for example, edit the file Worker to something like:

var segundos = 20;
var initiate = Date.now() + (1000 * segundos);//Tempo que deve terminar o loop

postMessage(new Date().toString());

while (Date.now() < initiate) {
    postMessage(new Date().toString());
}

Note that long loops lock the browser, but this would be an example of how to test the Worker, the effect will be the same for the html page layer, because being inside the WebWorker will not affect the browser and will not lock it , this is just another simulation of long processes. That is, within Worker you can have while or demo_workers.js long, but what matters is that they are just examples here and you should use Worker when the need arises, as I explained here:

So what I mean is to use Web Workers only when needed.

References:

01.02.2016 / 20:29
4

This example really does not make any difference. Both the main thread and the worker thread are doing virtually nothing.

But imagine that instead of the timedCount function only incrementing a value and posting a message ("light" operations), it has performed CPU-intensive operations, which takes a considerable amount of time. In this case, if you had this function running on the main thread (ie the UI thread), it would be possible for the browser to be "locked" - since the (single) thread is not available to receive user interactions. p>

When you place "heavier" processing on a web worker, the UI thread remains available to handle user actions, and the page is not "locked" while calculations are being made. When processing is ready to be rendered, the worker can send a pro-threaded message already with the processing result.

A concrete example: the PDF.js library is used to decode PDF files and display them on a web page . A PDF file can be relatively complicated, and parsing and parsing of your content can take a long time. This library does all the parsing in a worker, and when it needs to put some element in the UI (for example, blocks of text, image, fonts, etc.) the worker sends a message to the main routine of the library.

Regarding the comment "any process that has the possibility to affect the performance in the ui is ideal to use the worker": not necessarily. In a "traditional" programming environment, you have an operation to be performed, and it runs its parts sequentially - this would potentially hold the UI thread for a long time. But in the JS world, most operations that can take a long time (mostly access to storage and network operations) are asynchronous - you start the operation, it releases the thread , and when the answer is available your code continues. These types of operations can be executed on the main thread without any problems, since the processing time is very small. Remember that there is an overhead in using workers (messages, synchronization, etc.), and they are not a panacea for solving all application performance problems. Workers are useful in applications that need a lot of CPU time **, not operations that can take a long time.

    
01.02.2016 / 19:04