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

Asked

Viewed 2,794 times

13

I was taking a look at some HTML5 features and came across this 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 couldn’t tell the difference between that and setInterval and setTimeout. As far as I know, these two dispute the JS thread, allowing the time programmed to run behind or something like that, and if you have a very low execution interval, can greatly affect the performance of the page, right?

Then I looked at the example that the W3S has on its website and lo and behold I come across this:

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();

Inside this web Workers, has a setTimeout, that each 500ms send to the page an update of the value I. So why not use directly the setTimeout? That doesn’t make sense to me. Someone can give a light, a jedi council?

Thank you.

2 answers

11


The setInterval

The setInterval is an asynchronous loop within the current javascript process, i.e., it runs on the same layer as the larger process although it does not need to wait, however if there are many calls setInterval or the callback inside the setInterval for too long it will anyway crash the browser (or tab, there are browsers like Chrome and Firefox Developer Edition that use multi-process).

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

The setTimeout

This is almost identical to the setInterval and also runs on the same layer of the current browser process or tab, the difference is that it is only fired once and the clearTimeout does not finish repeats only, it can finish a timeout midway.

The Web Worker

The Web Worker runs on an isolated layer being more similar to a Thread in fact, so much so that is not possible control or access DOM elements directly by Worker because they are different layers, it is necessary to work with signs (similar to the idea of Forms in C++ for example) is as if the file .js called in Worker I was in a separate browser, so with postMessage you send answers and with worker.addEventListener('message', ...); you capture, from both sides.

Exemplifying:

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

  • To the baz.js send a message to foo.html he’ll have to use self.postMessage and the foo.html will have to have an event like this worker.addEventListener('message', ...);.

Note also that the Web Worker not supported by some older browsers.

In short

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

You should use Worker almost run long and usually synchronous processes that easily freeze a page.

Answering to the doubt

The setTimeout within the Worker was just to simulate a long process, does not mean that it is something real, is to understand how the Worker works, you could have created a loop inside while giant in Worker that would have the same effect, for example edit the file demo_workers.js for 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 layer of the html page, 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 inside the Worker you can have setInterval or while long, but what matters is that they here are just examples and you should use the Worker when there is a need, as I explained here:

So what I mean is use Web Workers only when necessary.

References:

  • 1

    Got it, so even though having a setInterval inside the worker, it won’t dispute with the main thread and not have a chance to lock the ui, thus making a better experience for the user. In terms of performance, it consumes a lot of memory and processing?

  • @Paulogustavo this yourself you understood well. Consumption varies from browser to browser and depends on your application.

5

In this example it really doesn’t make any difference. Both the main thread and the worker thread are doing virtually nothing.

But imagine that instead of function timedCount just increment a value and post a message ("light" operations), it would be performing CPU-intensive operations, something that takes considerable time. In this case, if you had this function run on the main thread (i.e., the UI thread), it would be possible for the browser to be "locked" - since the (single) thread is not available to receive user interactions.

When you put the "heavy" processing on a web worker, the UI thread remains available to suit the user’s actions, and the page does not get "stuck" while the calculations are being made. When the processing is ready to be rendered, the worker can send a message to the main thread already with the processing result.

A concrete example: the library PDF.js is used to decode PDF files and display them on a web page. A PDF file can be relatively complicated, and doing Parsing and analyzing its 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, text blocks, image, fonts, etc.) the worker sends a message to the main library routine.

Regarding the comment "any process that has the possibility of affecting the performance in the ui is ideal to use the worker": not necessarily. In a "traditional" programming environment, you have an operation to perform, and you run your 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 (mainly accesses to Storage and network operations) are asynchronous - you start the operation, she releases the thread, and when the answer is available your code continues. These types of operation can be executed on the main thread without problems, since the time of processing is very small. Remember that there is an overhead in using Workers (messages, synchronization, etc.), and they are not a panacea to solve all performance problems of the application. Workers are useful in applications that need a lot of **CPU time, not operations that may take.

  • So, the web worker used a single, exclusive thread of his? In this case, any process that has the possibility to affect ui performance is ideal to use the worker?

  • Updating the answer, since the explanation of this is a bit long...

Browser other questions tagged

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