Web worker
Web worker defines an API for running scripts in the background independently of any user interface scripts.
This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.
Web workers are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one web worker for each pixel of a four megapixel image.
Generally, web workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.[1]
Example
The simplest use of web workers is for performing a computationally expensive task without interrupting the user interface.
In this example, the main document spawns a web worker to compute prime numbers, and progressively displays the most recently found prime number.
The main page is as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Worker example: One-core computation</title>
</head>
<body>
<p>The highest prime number discovered so far is: <output id="result"></output></p>
<script>
var worker = new Worker('worker.js');
worker.onmessage = function (event) {
document.getElementById('result').textContent = event.data;
};
</script>
</body>
</html>
The Worker()
constructor call creates a web worker and returns a Worker
object representing that web worker, which is used to communicate with the web worker. That object's onmessage
event handler allows the code to receive messages from the web worker.
The web worker itself is as follows:
var n = 1;
search: while (true) {
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
postMessage(n);
}
To send a message back to the page, the postMessage()
method is used to post a message when a prime is found.[1]
References
- ↑ 1.0 1.1 "Web Workers". WHATWG. http://www.whatwg.org/specs/web-workers/current-work/. Retrieved 30 October 2009.
Stub icon | This Internet-related article is a stub. You can help Wikipedia by expanding it. |
If you like SEOmastering Site, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...