HTML - Web Worker


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!


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('');
  • That object's onmessage event handler allows the code to receive messages from the worker.
worker.onmessage = function (event) {
     document.getElementById('result').textContent =;

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

Documentation / Reference

Powered by ComboStrap