I am following a tutorial on web worker at - http://www.w3schools.com/html/html5_webworkers.asp
Most of the things are clear to me but I don't know what is the purpose of using setTimeout
function and how postMessage(i)
is returning the value of i
to w.onmessage
.
Code -
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
Can anyone please explain me the flow how this example is working ?
The purpose of setTimeout
is to call timedCount
after 500 ms. Since it is called recursively, the effect is that timedCount
is called twice in each second.
Note also, that this would do the same:
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
}
setInterval(timedCount, 500);