HTML5: A multi-threading approach with Web Workers

The word Web Worker specifies a JavaScript running in the background, without affecting the performance of the page, independently of other user-interface scripts that may also have been executed from the same HTML page.

Let’s go into little depth to understand what it exactly means :).

Javascript will hang the browser, where the code written by us requires a high CPU utilization. When executing scripts in a Web page, the page becomes unresponsive until the script is finished and shows “unresponsive script” alert message.

ummm … 😡 we should check one example, to better understand, what I want to say here!!!

<!DOCTYPE HTML>
<html>
    <head>
        <title>Big loop test</title>
        <script>
            function loopTest() {
                for (var i = 0; i <= 10000000000; i++){
                    var j = i;
                }

                alert("Completed " + j + "iterations" );
            }

            function sayTime() {
                var d = new Date();
                var hour = d.getHours();
                var minute = d.getMinutes();
                var second = d.getSeconds();

                alert(hour + ':' + minute + ':' + second);
            }
        </script>
    </head>
    <body>
       <input type="button" onclick="loopTest();" value="Check For Loop" />
       <input type="button" onclick="sayTime();" value="Get Current Time" />
    </body>
</html>

If we run the above code, and click both the button one by one, we will get the following error alert message, as because CPU will be busy running the loop and wait for the completion of that task.

Screen Shot 2014-10-09 at 11.54.21 am

So, what should we do now ❓ … Do we really have any idea, how to fix this type of issue :-(.

Hmmm… 💡 Yes, I guess we can do so using Web Workers 🙂 😎

Web Workers allow for concurrent execution of the browser threads, which will do all the computational tasks without interrupting the user interface and run on separate/different threads. That means, we can continue to do whatever we want: clicking, selecting things, loading images etc., while the web worker runs in the background.

Sounds interesting 😎 🙂

Process :-
Web workers interact with the main document via message passing. The following code illustrates about how Web Worker works.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Big for loop</title>
        <script>
            var worker = new Worker('checkLoop.js');

            if(typeof(Worker) !== "undefined") {
                worker.onmessage = function (event) {
                    alert("Completed " + event.data + "iterations" );
                };

                function sayTime() {
                    var d = new Date();
                    var hour = d.getHours();
                    var minute = d.getMinutes();
                    var second = d.getSeconds();

                    alert(hour + ':' + minute + ':' + second);
                }
            } else {
                alert('Your browser does not support Web Worker');
            } 

            
        </script>
    </head>
    <body>
       <input type="button" onclick="sayTime();" value="Get Current Time"/>
    </body>
</html>

checkLoop.js

for (var i = 0; i <= 1000000000; i++){
   var j = i;
}
postMessage(j);

if(typeof(Worker) !== "undefined") { ... }

This code checks for the Browser support of Web Worker.

var worker = new Worker('checkLoop.js');

This code is used for initializing Web Worker with the URL of a JavaScript file, which contains the code the worker will execute. If the specified javascript file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. If the path does not found, the worker will fail silently.

worker.onmessage = function (event) { ... }

This code sets event listeners and communicates with the script that spawned it from the main page.

Terminate a Web Worker :-

worker.terminate();

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated. So, need to use the above code to terminate a Web Worker.

Reuse the Web Worker :-

worker = undefined;

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

Note :- Since web workers are in external files, they do not have access to the following JavaScript objects.

  • Parent Object
  • Window Object
  • Document Object

Note :- Please check here for Browser support details.

Thanks 🙂 and will be happy to listen from you 🙂 :).

Advertisements

One thought on “HTML5: A multi-threading approach with Web Workers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s