HTML and CSS Reference
In-Depth Information
To provide an option to stop the worker process, you need to implement the terminate
method. Add a button to the page like so:
<input id="stopWorker" type="button" value="Stop Work" />
And add the following script beneath the postMessage call:
document.getElementById("stopWorker").onclick = function () {
worker.terminate();
}
Next, click the Do Work button followed by the Stop Work button to see that the work is
terminated and no result is returned.
Understanding web worker limitations
Web workers are very convenient. They can solve many processing problems in intensive web
applications. However, be aware of the limitations imposed on workers as well.
Passing parameters
The postMessage method accepts a parameter that enables it to pass data to the worker that
it might need to operate on or with. The postMessage parameter is a string—it can take any
serializable object such as native data types, JSON objects, or XML. The parameter can't be a
function.
In the bouncing ball example, the input for what number to work with could come from
users. An input box can be added to the HTML and the entered value can be passed to the
worker. This would look like this:
var value = document.getElementById("inputValue").value;
worker.postMessage(value);
Then in the worker, the value would be accessed like this:
onmessage = function (evt) {
var work = evt.data;
}
The function receives an event object with a property called data that contains whatever
was passed into the worker.
Number of workers
Although no limit is imposed on how many workers can be processed or created concurrently,
the number of workers used is something that you need to be pay attention to. Creating
workers is a heavy operation. Each worker creates threads at the operating system level and
their use should be managed accordingly. If you want a high volume of workers, consider
 
 
Search WWH ::




Custom Search