Introduction: JavaScript Web Workers

About: Nowadays attempting creating small apps to dive into the world of programming and Software Development

This tutorial is building on the previous instructable with the calculation spreadsheet generator.

You probably realized that the whole app locks up if it is creating a huge spreadsheet of e.g. 3000x3000 rows and columns. The problem is showed in the following diagram.

Step 1: The Cause of the Lockup

The app is running sequentially in a queue, at first it reads the user input and the arguments are assigned to the calculation constructor. After calculation is finished dom is finally accessible.

If the script takes too long the browser shows a freezing warning.

Step 2: The Solution

In background (e.g. for complex calculations, algorithms) you can use WebWorkers so that you can seperate the "work" from the main thread of JS.

Step 3: Changes of the Previous Tutorial

We delete the calcCSV.js file and create a new one called workerCalc.js in the worker directory.

Step 4:

Then we delete the path to the calcCSV file otherwise, require.js will show an error that the file is missing.

Step 5: Small Changes in the Controller File

We replace a line of the previous object with a new Worker instance:

let worker = new Worker('worker/workerCalc.js');

Then the arguments will be passed to the worker as message (postMessage) and with onmessage you will get the result.

Step 6: The Implementation of the WebWorker

The content of the worker looks similar to the previous tut from calcCSV.js, it is not a class file, there are funtions implemented like in "old style" JavaScript. The methods are the same, small changes are done (mostly variable declarations locally).

The worker takes a message (can be a variable, an array or json) that works like passing arguments and processes them. It sends a postmessage back, if the calculation is finished. You retrieve the results with onmessage on the controller side like mentioned in the previous step.

Step 7: Only a Small Change and It's Finished

The empty downloadString that I forgot to initialize in the previous tut.

Related to Chrome browser if you start a worker locally as file:

http://stackoverflow.com/questions/21751775/web-wo...

parameter: --allow-file-access-from-files

...and here is the finished worker app as zip.