Java Reference
In-Depth Information
a new file called factors.js that's saved inside the js folder. Remove the factorsOf()
function from the scripts.js file and add it into this file. We'll be adding more to this file
later, but first we need to edit the factorize() function in the scripts.js file so that it
contains the following:
js/factors.js (excerpt)
function factorize(event) {
event.preventDefault(); // prevent the form from being
submitted
var number = form.number.value;
if(Worker) {
worker = new Worker("link/to/file/factors.js");
worker.postMessage(number);
worker.addEventListener('message', function(event) {
document.getElementById("output").textValue =
event.data;
}, false);
}
}
After checking whether web workers are supported, it adds a new web worker. It then uses
the postMessage() method to send a message to the worker, which is the number that
we want to factorize. When the number has been factorized the worker will send a message
back to say it has finished.
To deal with this, we set up an event listener that will fire when a message is received back
from the worker. The information sent from the worker is stored in the data property of
the event object, so we use the textValue property to insert the data into the output
div.
Search WWH ::




Custom Search