Java Reference
In-Depth Information
Now we go back to the factors.js file and add this event listener code to the end of the file:
js/factors.js (excerpt)
self.addEventListener('message', function(event) {
var factors = String(factorsOf(Number(event.data)));
self.postMessage(factors);
self.close();
}, false);
This will fire when the worker receives a message, occurring when the form is submitted.
The number to be factorized is stored in the event.data property. We use the factor-
sOf() function to find the factors of the number; then convert it into a string and send a
message back containing the answer. We then use the close() method to terminate the
worker, since its work is done.
Now if we test the code out, it will still take a long time to factorize a long number, but
the page will not freeze. You can also continue to change the background color while the
factors are being calculated in the background.
Note: Use a Server
The file containing the worker code is expected to be hosted on a server.
This is the best option, but if you want to run an example locally you need
to turn off the same origin policy setting in the browser.
Shared Web Workers
The examples we have seen so far are known as dedicated web workers . These are linked
to the script that loaded the worker and are unable to be used by another script. You can
also create shared web workers that allow lots of different scripts on the same domain to
access the same worker object. Read more about shared web workers at SitePoint.
Web workers allow computationally complex operations to be performed in a separate
thread, meaning that the flow of a program won't suffer interruptions and an application
will not freeze or hang. They are a useful feature that help to keep sites responsive, even
Search WWH ::




Custom Search