A worker is a script that run in the background independently of any user interface scripts.
They can run in parallel to their main page. This allows for thread-like operation with message-passing as the coordination mechanism.
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.
The simplest use of workers is for performing a computationally expensive task without interrupting the user interface.
The 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);
}
where:
Worker example: One-core computation
<p>The highest prime number discovered so far is: <output id="result"></output></p>
var worker = new Worker('https://datacadamia.com/doku.php?do=export_code&id=web:html:worker&codeblock=0');
worker.onmessage = function (event) {
document.getElementById('result').textContent = event.data;
};
More example (With IO, …): Web Workers examples