Click here to Skip to main content
14,270,361 members

HTML5: A Multi-threading Approach with Web Workers

Rate this:
4.71 (8 votes)
Please Sign up or sign in to vote.
4.71 (8 votes)
9 Oct 2014CPOL
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!!!

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

<!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 is 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, 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)

Share

About the Author

Prava-MFS
Software Developer (Senior)
India India
Software engineer with around 6 years of web application development experience in open source technologies like PHP, MySQL, HTML, HTML5, CSS, CSS3, Javascript, jQuery etc.

I love to learn and share my knowledge in which manner I can and like to solve the issues as in the coding perspective. I am an active contributor in community forums like StackOverflow, CodeProject etc. Besides that, I write blogs in free time and speak in various technical community events.

Comments and Discussions

 
QuestionA way to know how many worker are launched ? Pin
gordon8810-Oct-14 22:18
professionalgordon8810-Oct-14 22:18 
QuestionAnd within same script ? Pin
gordon8810-Oct-14 22:16
professionalgordon8810-Oct-14 22:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Technical Blog
Posted 9 Oct 2014

Tagged as

Stats

11.8K views
11 bookmarked