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.
Related : http://answall.com/questions/90078/loop-em-fun%C3%A7%C3%A3o-calling-herself/90086#90086
– Guilherme Lautert
Related: What is the real advantage of using a Callback and what is thread/multithread?
– Guilherme Nascimento