How To Use Javascript Workers – Simple Examples

Welcome to a quick tutorial and examples on how to use Javascript workers. So you have heard of Javascript workers and their “threading powers”. But just how do we create and use Javascript workers?

The basic usage of Javascript workers is somewhat similar to including an external Javascript file.

  1. Create a “standalone” Javascript file that you want to run as a worker.
  2. Then, simply create a worker object. For example, var work = new Worker("SCRIPT.JS").

That’s all, and the script will now run in a new thread. But there’s more than meets the eye, let us walk through some examples in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Javascript Workers Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Take note that workers will not work with file://, you need to use http://.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

JAVASCRIPT WORKERS

All right, let us now get into the example of Javascript workers in this section.

 

1) SIMPLE WORKER & RESTRICTIONS

MAIN SCRIPT

1a-main.html
<!-- (A) JAVASCRIPT -->
<script>
// (A1) DUMMY VARIABLE
var foo = "bar";

// (A2) CREATE WORKER
var work = new Worker("1b-worker.js");
</script>
 
<!-- (B) DUMMY HTML -->
<p id="foo">Bar</p>

This should be very straightforward – Creating a Javascript worker is as easy as new Worker("SCRIPT.JS").

 

WORKER SCRIPT

1b-worker.js
// (A) DO PROCESSING JUST LIKE "NORMAL JS"
var num = 1 + 1;
console.log(num);

// (B) PROBLEM - CANNOT ACCESS "MAIN SCRIPT" VARIABLES
console.log(foo); // NOT DEFINED

// (C) PROBLEM - CANNOT ACCESS DOM
var el = document.getElementById("foo"); // DOCUMENT NOT DEFINED

A worker script is still Javascript, and it pretty much works “as usual”. But take extra note that worker scripts are “standalone”:

  • Worker scripts will not “inherit” the functions and variables in the main script.
  • Worker scripts do not have access to the DOM. I.E. Cannot directly manipulate the HTML elements.

 

 

2) WORKERS ACT LIKE “AJAX”

MAIN SCRIPT

2a-main.html
 <!-- (A) DUMMY HTML FORM -->
<form onsubmit="return demo()">
  <input type="text" id="user-name" value="John Doe"/>
  <input type="email" id="user-email" value="john@doe.com"/>
  <input type="submit" value="Go!"/>
</form>
 
<!-- (B) JAVASCRIPT -->
<script>
function demo () {
  // (B1) CREATE A NEW WORKER
  var work = new Worker('2b-worker.js');

  // (B2) DO THIS ON WORKER RESPONSE
  work.onmessage = function (evt) {
    console.log("Worker has responded");
    console.log(evt.data);
  };

  // (B3) OPTIONAL - MANAGE ERRORS
  work.onerror = function (error) {
    console.log("Worker script error!");
    console.log(error);
  };

  // (B4) SEND DATA TO WORKER
  work.postMessage({
    name: document.getElementById("user-name").value,
    email: document.getElementById("user-email").value
  });
  return false;
}
</script>

So how the heck do we pass variables to a worker? How can we get the results back from a worker? The easiest way is to think of workers like an AJAX call, send data to the worker, let it process, and do something on response.

  • B4 – Use work.postMessage() to send data to the worker script.
  • B3 – work.onerror() is optional, handle any errors.
  • B2 – Lastly, specify work.onmessage() to do something when the worker responds.

 

 

WORKER SCRIPT

2b-worker.js
// (A) PROCESS ON RECEIVING DATA FROM MAIN SCRIPT
onmessage = function (evt) {
  console.log("Worker has received data");
  console.log(evt.data);
 
  // (B) DO PROCESSING
  var foo = `${evt.data.name} - ${evt.data.email}`;
 
  // (C) RESPOND
  postMessage({
    status: 0,
    message: "OK"
  });
};

Yep, this should be no problem –

  • onmessage The worker only starts processing on receiving data from the main script.
  • postMessage Return the results or respond to the main script.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

THE SUMMARY

New Worker
var work = new Worker("SCRIPT.JS") Create a new worker object.
Sending Data – From Main To Worker
work.postMessage(DATA) Send data to the worker.
onmessage = function(evt){ evt.data } On receiving data in the worker script.
Sending Data – From Worker To Main
postMessage(DATA) Send data back to the main script.
work.onmessage = function(evt){ evt.data } On receiving data in the main script.
Error handling
work.onerror = function(err){ ... } Handle worker errors that are thrown.

 

 

EXTRA) ASYNC FUNCTIONS VS WORKERS

Here’s a quick one for those who are curious –

  • Asynchronous functions are single-threaded within a process.
  • While workers are multi-threaded. In a way, we can say that the workers run “truly parallel to each other”.

P.S. Some of you sharp code ninjas may have noticed. How can something be single-threaded and still be asynchronous? Shouldn’t it be linear? Here is a good article that I found to explain it best (if you want to read later) – How is javascript asynchronous AND single-threaded?

 

EXTRA) MULTI-THREADING HICCUPS

Workers may seem to be the miracle pill for system performance, but there is a possible critical flaw when it comes to clashes in computations. Watch this video if you are interested.

 

INFOGRAPHIC CHEAT SHEET

Javascript Workers Example (Click to Enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *