JavaScript Web Workers

by sphere360 in Circuits > Software

911 Views, 3 Favorites, 0 Comments

JavaScript Web Workers

ww.png

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.

The Cause of the Lockup

noworker.png
freeze.png

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.

The Solution

wworker.png

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.

Changes of the Previous Tutorial

dirchange.png

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

changes0.png

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

Small Changes in the Controller File

changes1.png

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.

The Implementation of the WebWorker

worker.png

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.

Only a Small Change and It's Finished

changes2.png

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.