Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Web Workers: How to bring Threading to JavaScript?

In this tutorial, we take a look into how web workers are the means to implementing multi-threading capabilities to JavaScript, a feature that allows for faster and uninterrupted user experience.

When it comes to development using JavaScript, it certainly happens to be among the most important scripting languages that are used by developers. Despite being rich in features, JavaScript is certainly a language that happens to follow a single threaded approach.

However, this certainly has its drawbacks. For example, if you have lengthy block of JavaScript running code on your browser window, taking care of numerous tasks, then it is obvious that it can result in the page being frozen. Once this happens, the user will then need to kill the tab or the session. Thus, it leads to a very bad user experience, which is also not good for your website.

This is precisely where a multithreading approach can be very helpful and we implement that with the help of HMTL5 web workers.

If you want to get more into those subjects, take a look at our JavaScript/CSS/HTML5 courses:

What are these web workers?

Primarily, a web worker is just a JavaScript that runs in the background, but at the same time does not affect the performance aspects of the page in any manner. Therefore, with the implementation of a web worker, it can run at the back independently of the other scripts, and allowing you to perform operations like selecting, clicking and more.

What is the primary application of web workers?

As it has been mentioned earlier, web workers generally make way for a multithreaded approach to running JavaScript.

Browsers these days come with a sort of protection mechanism that always alerts the user when a long script starts to run. However, what it does not differentiate is whether a certain script has been incorrectly written, or if it just about needs a long time to accomplish its task. Also, during such a time the utilization of the computer’s processor is also pretty large and that can result in a frozen page. Thus, if you wish to negate such kinds of warnings and unresponsiveness, it is important to run JavaScript codes in the background, which is exactly why we need web workers.

Listing 1: Unresponsive script

<!DOCTYPE HTML>
<html>
    <head>
        <title>Large Loop Test</title>
        <script>
            function looptest() {
                for (var a = 0; a <= 1000000000; a++){
                    var b = a;
                }
 
                alert("Completed " + b + " number of iterations" );
            }
 
            function saytime() {
                var c = 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 the Loop" />
       <input type="button" onclick="saytime();" value="Get the Current Time" />
    </body> 
</html> 

The above given example is one such type of code that will display an error message if we run it and then clicks on both buttons one after another. This is simply because the CPU will run the keep itself busy with the running of the loop and wait until the task is completed.

Figure 1: Unresponsive script warning

Use of setTimeout() and setInterval()

In order to counter the problem of a frozen page resulting from a long running JavaScript code, developers have often relied on using setTimeout() and setInterval() functions. However, despite the fact that they run in the background, they still follow a single threaded approach.

Here’s a little example demonstrating the use of setTimeout() and setInterval() -

Listing 2: Usage of setTimeout() & setInterval()

 
<!DOCTYPE html>
<html>
<head>
</head>
<body>
   <p id="p"></p>
   <script type="text/javascript">
      var j = 0,p = document.getElementById('p');
      var EgInterval = setInterval(function() {
         p.textContent = j++;
         if (j > 20) {
            clearInterval(EgInterval);
         }
      }, 80);
      alert("There shall be no writes on the document until you close the alert box.");
   </script>
</body>
</html> 

When you run the above code in the browser, you will see that there will be no writes performed unless you dismiss the alert box. This is why HTML5 employs the use of web workers.

Checking for support of web workers?

Before we move on to the creation of web workers, it is important that we also check as to whether a browser is capable of running web workers.

if(typeof(Worker) !== "undefined") {
     // Yes! Web worker is supported o this browser!
     // Any code.....
 } else {
     // Sorry! There is no Web Worker support for this browser.
 }

Some points to note about Web workers

  • Web Worker APIs permit and lay out methods that can help run scripts in the background. One can have tasks in threads that run excusive to the primary page, thus not affecting the performance.
  • Not all algorithms may be suitable to follow a parallel approach. Thus, certain vlocks of JavaScript code may not be able to take advantages offered by web workers.
  • Since web workers largely work on separate threads, they require to be stored in completely different files to the main page. You can basically instantiate a worker object that allows you to call the web worker into action.
  • Web workers and the main page are known to communicate by means of messages. You can use JSON or normal strings to form those messages.
  • A web worker stays alive and working until it is killed.

Accessible elements from Web workers

Here is a list of methods that you can access from a web worker.

  • void close() – for terminating a worker thread
  • void importScripts(urls) – list of additional JavaScript files
  • void postMessage(data) – used to send messages to or from a worker thread
  • void clearInterval(handle) – used for cancellation of a timeout that is identified by the handle
  • void clearTimeout(handle) – used for cancellation of a timeout identified by a handle
  • long setInterval(handler, timeout value, arguments) – used for setting a timeout that runs repetitively after certain intervals. Additional arguments can also be directly passed to the handler.
  • long setTimeout(handler, timeout value, arguments) - used for setting a timeout that runs repetitively after certain intervals. Additional arguments can also be directly passed to the handler.

Creating a Web worker file

We now go ahead and create a web worker in an external JavaScript file. Basically, the code below is a simple script that acts as a counter. You can save it with a file name you please.

Listing 3: demowebworker.js

var a = 0;
 
 function timecount() {
     a = a + 1;
     postMessage(a);
     setTimeout("timecount()",400);
 }
 
 timecount();

The postMessage() method that is defined in the above code is mainly responsible for carrying a message back to the main HTML page.

Creating a Web worker object

Now that we have created a simple web worker script, it is useless unless we call it into action from a separate HTML file. However, we first need to create an object if we are to do so.

if(typeof(web) == "undefined") {
     web = new Worker("demowebworker.js");
 }

This piece of code primarily checks if an object for a web worker already exists, and if not, it creates a new object and then runs the code.

Also, in order to convey messages to and fro from a web worker, it is important to on message event listener, which does the job. Whenever a web worker posts a message, the event listener executes and stores the data conveyed by the worker.

web.onmessage = function(event){
     document.getElementById("result").innerHTML = event.data;
 };   

Termination of a Web worker

A web worker basically continues to run and listens to messages even after the external script may have finished running. Thus, it is always necessary to terminate a web worker. Now, that can be done by the use of terminate() function.

web.terminate(); 

Reusing a Web worker

After you have terminated a web worker, it can be reused. This can be achieved by simply using the following line of code.

web = undefined;

HTML Code for Web worker implementation

We have already gone through how a web worker can be created as a JavaScript file and also certain features surrounding it. Here we take a look at the HTML code that implements a web worker.

Listing 4: webworks.html

<!DOCTYPE html>
 <html>
 <body>
 
 <p>Counting the Numbers: <output id="result"></output></p>
 <button onclick="startworker()">Start the Worker</button> 
 <button onclick="stopworker()">Stop the Worker</button>
 <br><br>
 
 <script>
 var web;
 
 function startworker() {
     if(typeof(Worker) !== "undefined") {
         if(typeof(web) == "undefined") {
             web = new Worker("demowebworker.js");
         }
         web.onmessage = function(event) {
             document.getElementById("result").innerHTML = event.data;
         };
     } else {
         document.getElementById("result").innerHTML = "Sorry! There is no Web Worker support.";
     }
 }
 
 function stopworker() { 
     web.terminate();
     web = undefined;
 }
 </script>
 
 </body>
 </html> 

Figure 2: Output of web worker

DOM and Web workers

Web workers are implemented in external files and thus, they do not have access to the window, document and parent JavaScript objects.

Uses of Web workers

Web workers find numerous uses in current development work.

Generally, they are very much used in parallel processing, such as rendering UI, collecting data and recording events. Then they are also used for Web/IO by polling URLs in the background. Movement tracking can also be carried out by means of web workers.

Besides these, there are also several other areas where web workers may be employed as per requirements.

Conclusion

The tutorial designed above gives you a look into the basics surrounding web workers and takes you through how they can be implemented. Also, certain functions that surround the use of web workers have also been shown and explained. Lastly, a full example has also been provided, so as to aid in the process of learning how a real life application may work.

With the correct application of web workers for your web pages, you can certainly improve on their performances vastly.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login