Web Worker API

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

Web Workers API

A web worker is JavaScript that runs in the background, without affecting the performance of the page.

What is a Web Worker?

When executing scripts on an HTML page, the page becomes unresponsive until the script is finished.

A web worker is JavaScript running in the background, independently of other scripts, without affecting the performance of the page. You can to do activities like: clicking, selecting things, etc., while the web worker runs in the background.

Web Workers Example

The example below creates a simple web worker that counts numbers in the background.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Web Workers API</h2>

<p>Count numbers: <output id=”result”></output></p>

<button onclick=”startWorker()”>Start Worker</button>

<button onclick=”stopWorker()”>Stop Worker</button>

<script>

let w;

function startWorker() {

if(typeof(w) == “undefined”) {

w = new Worker(“demo_workers.js”);

  }

 w.onmessage = function(event) {

 document.getElementById(“result”).innerHTML = event.data;

  };

}

function stopWorker() {

  w.terminate();

  w = undefined;

}

</script>

</body>

</html>

Check Web Worker Support

To create a web worker, always make sure to check whether the user’s browser supports it:

Example

if (typeof(Worker) !== “undefined”) {

  // Yes! Web worker support!

  // Some code…..

} else {

  // Sorry! No Web Worker support..

}

Create a Web Worker File

Create a web worker in external JavaScript.

Here, we create a script that counts. The script is stored in the “demo_workers.js” file:

Example

let i = 0;

function timedCount() {

  i ++;

  postMessage(i);

  setTimeout(“timedCount()”,500);

}

timedCount();

The important part of the code above is the postMessage() method – which is used to post a message back to the HTML page.

Create a Web Worker Object

After the web worker file, call it from an HTML page.

The following lines check if the worker already exists, if not – it creates a new web worker object and runs the code in “demo_workers.js”:

Example

if (typeof(w) == “undefined”) {

  w = new Worker(“demo_workers.js”);

}

Then we can send and receive messages from the web worker.

Add an “onmessage” event listener to the web worker.

w.onmessage = function(event){

 document.getElementById(“result”).innerHTML = event.data;

};

When the web worker posts a message, the code inside the event listener is executed. The data from the web worker is stored in event.data.

Terminate a Web Worker

When a web worker object is created, it continues to listen for messages (even after the external script is finished) until it is terminated.

To terminate a web worker, and free browser/computer resources, use the terminate() method:

w.terminate();

Reuse the Web Worker

If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

Full Web Worker Example Code

We have already seen the Worker code in the .js file. Below is the code for the HTML page.

Example

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Web Workers API</h2>

<p>Count numbers: <output id=”result”></output></p>

<button onclick=”startWorker()”>Start Worker</button>

<button onclick=”stopWorker()”>Stop Worker</button>

<script>

let w;

function startWorker() {

if(typeof(w) == “undefined”) {

w = new Worker(“demo_workers.js”);

  }

 w.onmessage = function(event) {

 document.getElementById(“result”).innerHTML = event.data;

  };

}

function stopWorker() {

  w.terminate();

  w = undefined;

}

</script>

</body>

</html>