QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Multithreading In HTML5 Using Web Workers

Multithreading In HTML5 Using Web Workers

web-worker

This post is a part 22 of Multithreading In HTML5 Using Web Workers post series.

Multithreading allows us to execute code simultaneously by decreasing the context switching overhead. Multithreading is supported by all programming languages and platforms. But HTML never supported it. HTML programmers had to use setTimeout or setInterval to make the application behave like multithread application. But HTML5 provided built in API to support multithreading.


What is HTML5 Web Worker?

HTML5 Web Worker is a JavaScript thread(or javascript file) than runs concurrently with the main thread. This child threads(workers) cannot access any resource(window, document and parent objects) of the main thread. Worker thread have their own context and work independently than the main thread. Web workers allows parent and child threads to communicate with each other via message passing.

Types Of HTML5 Web Worker

Web Workers are of two types: Dedicated Web Workers and Shared Web Workers. They both provide multithreading functionality but differ in the way used and features they provide.

In this article we will learn about dedicated web workers. Shared web workers are not supported by IE and many other mobile browsers, therefore there is no point of learning and implementing it.

Dedicated Web Workers

These are the points you need to remember while working with dedicated web workers:

  • Created, managed and stopped by a single main main thread.
  • worker thread stops as soon as the parent thread ends.
  • Errors occurred during child thread execution is reported to the parent thread.
  • Created using window.Worker class and started using postMessage(). Messaging passing is done using postMessage().

Let’s see an working example of dedicate web worker

index.html

<!doctype html>
<html>
<head>
    <title>Test for Web Workers</title>
    <script type="text/javascript">
    {
        //this function is used to check if dedicated web workers are supported by your browser or not.
        function body_loaded()
        {
            //window object has a class called Worker
            if(window.Worker != undefined)
            {
                //browser supports
                window.document.getElementById("supported").style.display = "block";
            }
            else
            {
                window.document.getElementById("unsupported").style.display = "block";
            }
        }

        function clicked()
        {
            if(window.document.getElementById("input_text").value == "")
            {
                alert("Input a number");
            }
            else
            {
                //worker.js file is downloaded into a new thread
                var myWorker = new window.Worker('worker.js');

                //this is triggered when worker thread sends a message to main thread.
                myWorker.onmessage = function(event){

                    //event.data carries the information passed by the worker to main thread.
                    var value = event.data.value;
                    var errorMessage = event.data.errorMessage;

                    //worker can send its own custom errors. this is not a runtime error.
                    if(errorMessage)
                    {
                        alert("Error Occured: " + errorMessage);
                    }
                    else
                    {
                        alert("Sum of 10 to the number is: " + value);
                    }

                    //parent terminates the created worker.
                    myWorker.terminate();
                };

                //errors of the worker thread is handled in the parent thread.
                myWorker.onerror = function(error)
                {
                            error.preventDefault(); // prevent default error actions

                            //display error message, file name and line number.
                            alert(error.message + ' (' + error.filename + ':' + error.lineno + ')' );
                }

                var myValue = parseInt(window.document.getElementById("input_text").value);

                //postMessage is used to start the worker and also pass message to the worker thread.
                //you can pass a string or json to postMessage function.
                myWorker.postMessage({ value : myValue });
            }
        }
    }
    </script>
</head>
<body onload="body_loaded()">
    <div id="supported" style="display: none">
        <input type="text" id="input_text"><input type="button" value="Click to Add 10" onclick="clicked()">
    </div>
    <div id="unsupported" style="display: none">
        Unsupported
    </div>
</body>
</html>

add.js

function add(n)
{
    return n+10;
}

worker.js

/* you can import more scripts inside the worker context and run them. */
importScripts("add.js");

//triggered when parent sends the message using postMessage().
self.onmessage = function(event){
    var n = event.data.value;

    if(isNaN(n))
    {
        //send a custom error message to the main thread
        postMessage({ errorMessage : 'Not a number.', value : NaN });
       
        //worker termiantes itself.
        self.close();
    }
    else
    {
        n = add(n);
        //send the result to the parent thread.
        postMessage({ value : n});

        //worker termiantes itself.
        self.close();
    }
}

View Demo

Points to remember

You need to remember that an HTTPS page cannot run a HTTP worker.

javascript: and data: URLs cannot be used while creating web workers.

Main thread and worker thread must belong to same origin.

Jun 12, 2014Narayan Prusty
How To Detect Element Entered ViewportCreating Offline Applications using HTML5 Tutorial
Comments: 2
  1. Ankur
    5 years ago

    How can i use ajax code through webworker for changing time at every second without page refresh

    ReplyCancel
  2. Mosh
    6 years ago

    You can fix this: “//worker.js file is downloaded into a nre thread” to “//worker.js file is downloaded into a new thread”

    ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 6 Comments Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • What is HTML5 Web Worker?
  • Types Of HTML5 Web Worker
  • Dedicated Web Workers
  • Points to remember
Related Articles
  • Bypass Same Origin Policy
  • requestAnimationFrame Tutorial
  • Web Notification API Tutorial with Example
  • Speech Recognition and Synthesis Using JavaScript
  • Displaying And Highlighting Source code in HTML Page
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license