Java Reference
In-Depth Information
To post a message
from
the worker, the following is used in the worker script:
self.postMessage("Finished");
When a message is posted, a
message
event is fired, so they can be dealt with using an
event listener. The data sent with the message as an argument is stored in the
data
prop-
erty of the
event
object that's passed to the callback function. The following example
would log any data returned from the worker to the console:
worker.addEventListener('message', function(event) {
console.log(event.data);
}, false);
When a worker has completed its task, it can be stopped using the
terminate()
method
from within the main script:
worker.terminate();
Or using the
close()
method from inside the worker script:
self.close();
A Factorizing Example
Back in
Chapter 10
,
we created a function that found the factors of a given number. This
works well, but can take a long time to find the factors of large numbers. If it was used
in a website, it would stop any other code from running while it calculated the factors. To
demonstrate this, save the following code in a file called factors.htm:
factors.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Factorizor</title>
</head>
<body>
