About

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.

Example

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>
  • The Worker() constructor call creates a worker and returns a Worker object representing that worker, which is used to communicate with the worker.
var worker = new Worker('https://datacadamia.com/doku.php?do=export_code&id=web:html:worker&codeblock=0');
  • That object's onmessage event handler allows the code to receive messages from the worker.
worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
};

More example (With IO, …): Web Workers examples

Documentation / Reference