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.