HTML - Web Worker

> (World Wide) Web - (W3|WWW) > HyperText markup Language (HTML)

1 - 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.

Advertising

3 - Example

<!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 worker and returns a Worker object representing that worker, which is used to communicate with the worker. That object's onmessage event handler allows the code to receive messages from the worker.

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:

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

4 - Documentation / Reference

web/html/worker.txt · Last modified: 2019/02/09 11:29 by gerardnico