Posted on

I decided to come up with a web worker tutorial because while working on a project which requires the creation of NRIC(a citizen identifier used in Singapore, similar to social security number in the USA), I noticed that the UI freezes during the generation process.

This occurs because during the generation process, the UI thread is being used to generate the NRIC, resulting in the freezing of UI.

I looked into JavaScript “multi-threading” and web workers showed up most of the time.

With web workers, a second thread is used to handle the processing and therefore the UI does not freeze up.

Note: Since blob is used in this tutorial, you are required to use a web server in order for this example to work.

In this tutorial, we will be creating a program that will accept a value denoted by the variable maxNum which will be the upper limit.

Next, find the number of prime numbers that exist between **** and maxNum.

We will first create a template for our example.

<img style="width: 200px;" src="http://sierrafire.cr.usgs.gov/images/loading.gif" />
<button>Click me</button>

<script id="worker-js">
//some script
</script>
<script>
function main(){
//some function
}
</script>

The template above is pretty straight forward. We have a loading gif at line 4 (if the gif no longer exist in the future, feel free to use your own gif).

The gif file be used as a proof of concept that web worker is using a different thread. There are also two script tags starting on line 4 and line 7.

First, we will be working on the first set of script tag by referencing it to the main script.

<script>
    function main() {
        var workerJS = document.getElementById("worker-js").innerText;
        var blob = new Blob(\[workerJS\]);
        var blobURL = window.URL.createObjectURL(blob);
        var worker = new Worker(blobURL);

        worker.onmessage = function(event) {
            //event.data is value returned from the worker
        }
        worker.postMessage(100000);
    }
</script>

The value at line 11 will be the value for maxNum as mentioned earlier. In this case, we will be passing the value of 100000.

Now we will have to receive the integer on our worker, process it, and return the counter value to the main script.

<script id="worker-js">
    this.onmessage = function(event) {
        var maxNum = parseInt(event.data);
        var counter = 0;

        for (var i = 0; i & lt; maxNum; i++) {
            if (isPrime(i)) {
                counter++;
            }
        }
        postMessage(counter);
    }

    function isPrime(n) {
        for (var i = 2; i < n; i++) {
            if (n % i == 0) {
                return false;
            }
            return true;
        }

</script>

At line 3, we are accessing the integer by calling the data event.data and assigning it to the variable maxNum.

The isPrime function from line 14 to line 20 accepts an integer and return a boolean.

At line 6 to line 10, we will iterate the for loop from 0 to maxNum, checking if the integer is a prime number. If the integer in check is a prime number, we will increase the counter value by 1.

At line 11, we will then post this value back to the main script.

<script>
    function main() {
        var workerJS = document.getElementById("worker-js").innerText;
        var blob = new Blob(\[workerJS\]);
        var blobURL = window.URL.createObjectURL(blob);
        var worker = new Worker(blobURL);

        worker.onmessage = function(event) {
            var output = document.getElementById("result");
            output.innerHTML = parseInt(event.data);
        }

        worker.postMessage(100000);
    }
</script>

Lastly, we have added line 9 and 10 to display the returned value.

That’s it!

We have successfully implemented web workers into our program.

If you were to click the button, the gif will continue running while the number of prime number is being generated.

However, do remember that you are required to use with a web server in order for this example to work!