Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

HTML5: A Multi-threading Approach with Web Workers

4.71/5 (8 votes)
9 Oct 2014CPOL2 min read 18.2K  
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 a 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 … :mad: we should check one example, to better understand, what I want to say here!!!

HTML
<!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 buttons one by one, we will get the following error alert message, 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… :idea: Yes, I guess we can do so using Web Workers :) :cool:

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 :cool: :)

Process

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

HTML
<!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

JavaScript
for (var i = 0; i <= 1000000000; i++){
   var j = i;
}
postMessage(j);
JavaScript
if(typeof(Worker) !== "undefined") { ... }

This code checks for the Browser support of Web Worker.

JavaScript
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 is not found, the worker will fail silently.

JavaScript
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

JavaScript
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, we 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 I will be happy to hear from you :).

Image 2 Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)