How To Use Web Worker To Implement Thread In Javascript With Examples

This article will tell you how to use the web worker to implement thread programming in javascript. It will demonstrate the difference between using a web worker thread and not using a web worker thread when you implement the same function.

1. How To Use Web Worker To Implement Thread Programming In JavaScript Steps.

  1. Create an instance of the web Worker class, and pass the worker js file as the parameter to it.
    var worker = new Worker("html5-webworker-example.js");
  2. You should notice that you must browse the Html page that contains the above web worker js code from a web server not from a local Html file, if you browse the local Html file, you will encounter the error Exception : SecurityError: Failed to construct ‘Worker’ like below. You can read the article How To Fix Error Access To Script At From Origin ‘null’ Has Been Blocked By Cors Policy: Cross Origin Requests Are Only Supported For Protocol Schemes: Http, Data, Chrome, Chrome-extension, Chrome-untrusted, Https to learn more.
    Exception : SecurityError: Failed to construct 'Worker': Script at 'file:///D:/Work/dev2qa.com-example-code/PythonExampleProject/html/webworker/html5-webworker-example.js' cannot be accessed from origin 'null'.
  3. Define an anonymous function and assign the function to the web worker object’s onmessage property, then when the worker thread sends a message back to the worker object the function will handle it.
    worker.onmessage = function(event){
        var resultJSONstr = event.data;
    
        var resultJSONObj = JSON.parse(resultJSONstr);
    
        // show the calculate result in the message div.
        messageDiv.innerHTML = '<p>web worker result of 1 + 2....+ ' + numberStr + ' = ' + resultJSONObj.result + '</p>';
    }
  4. Call the web worker object’s postMessage(data) function to post the data to the web worker thread.
    worker.postMessage(numberInt);
  5. In the worker object javascript file (html5-webworker-example.js), define an anonymous function and assign the function to the onmessage property, then when you call the worker.postMessage(numberInt) function above, then it will trigger the below worker js thread onmessage event.
    // This function will handle the thread onmessage event when the web worker postMessage() function is invoked.
    onmessage = function(event){
    
        var result = 0;
    
        // get the post data from the event object.
        var numberInt = event.data;
    
    
        var startTime = new Date().getTime();
    
        // calculate the value.
        for(var i=1; i<=numberInt; i++){
            
            result += i;
    
            // the below source code will confirm that the calculation script thread is running on the backend.
            //if(i % 1000000000 == 0){
    
            //    console.log(i);
            
            //}
        }
    
        var endTime = new Date().getTime();
    
        var deltaTime = (endTime - startTime)/1000;
    
        console.log('web worker calculate used time : ' + deltaTime + ' seconds.');
    
        var resultJSONObj = {time:deltaTime, result:result};
    
        var resultStr = JSON.stringify(resultJSONObj);
    
        // post the value back to the web worker object, then it will trigger the web worker object's onmessage event function defined in the html5-webworker-example.html.
        this.postMessage(resultStr);
    }
    

2. How To Use Web Worker To Implement Javascript Thread Example.

  1. This example contains 2 source files.
    html5-webworker-example.html
    html5-webworker-example.js
  2. There is 1 input text box and 3 buttons in this example.
  3. You can input an integer number (n) in the input text box.
  4. When you click the first button, it will calculate the summary of 1 +2….+n in the current page javascript code, at that time you can find the web page is blocked and you can not click the Click Me button.
  5. When you click the second button, it will calculate the summary of 1+2…+n in the background web worker thread, the web page will not be blocked, and the Click Me button can be clicked。
  6. This is just the benefit of web worker thread programming, the back end task does not block the front end GUI actions.
  7. html5-webworker-example.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Html5 Using Web Worker To Implement Thread Example</title>
    <script type="text/javascript">
    
    // This function will not use the web wroker to calculate in thread.
    // So when the number is too big it can block the web page even crash the web page.
    function calculateWithoutWebWorker(){
    
        var messageDiv = document.getElementById('message');
    
        var numberStr = document.getElementById('calculateNumber').value;
    
        try{
    
            messageDiv.innerHTML = '<p>Calculating...</p>'
    
            var result = 0;
    
            var numberInt = parseInt(numberStr, 10);
    
            var startTime = new Date().getTime();
    
            for(var i=1; i<=numberInt; i++){
                
                result += i;
    
                // the below source code will confirm that the calculation script thread is running on the backend.
                //if(i % 1000000000 == 0){
    
                //    console.log(i);
    
                //}
            }
    
            var endTime = new Date().getTime();
    
            var deltaTime = (endTime - startTime)/1000;
    
            console.log('calculate not using web worker used time : ' + deltaTime + ' seconds.');
    
            messageDiv.innerHTML = '<p> result of 1 + 2....+ ' + numberStr + ' = ' + result + '</p>'
    
        }catch(exception){
    
            messageDiv.innerHTML = '<p> Exception : ' + exception + '</p>'
    
        }
    
    }
    
    
    
    // This function will use a web worker to implement the number calculation in a thread.
    // So it will block and crash the web page even the number is very very big.
    function calculateUsingWebWorker(){
    
        var messageDiv = document.getElementById('message');
    
        var numberStr = document.getElementById('calculateNumber').value;
    
        try{
    
            messageDiv.innerHTML = '<p>Calculating...</p>'
    
            // create a web wroker object, then it will run in a separate thread.
            var worker = new Worker("html5-webworker-example.js");
    
            // when the web worker receive the message send from the thread, then it will trigger the anonymous function defined here.
            worker.onmessage = function(event){
    
                var resultJSONstr = event.data;
    
                var resultJSONObj = JSON.parse(resultJSONstr);
    
                // show the calculate result in the message div.
                messageDiv.innerHTML = '<p> web worker result of 1 + 2....+ ' + numberStr + ' = ' + resultJSONObj.result + '</p>'
    
            }
    
            // get and parse the user input integer number.
            var numberInt = parseInt(numberStr, 10);
    
            // post the number to the web worker thread to calculate.
            worker.postMessage(numberInt);
    
        }catch(exception){
    
            messageDiv.innerHTML = '<p> Exception : ' + exception + '</p>'
    
        }
    
    }
    
    
    </script>
    
    
    <script type="text/javascript" src="html5-webworker-example.js" charset="utf-8"></script>
    <style>
        .block{
            display:block; 
            margin-top: 10px;
        }
    </style>
    </head>
    <body>
    <h3>Html5 Using Web Worker To Implement Thread Example.</h3>
    <div id="message" class="block"></div>
    <p class="block">Please input an integer number to calculate it's arithmetic progression value(1+....+n).
        <input type="text" id="calculateNumber"/></p>
    <button onclick="calculateWithoutWebWorker()">Calculate Without Web Worker</button>
    <button onclick="calculateUsingWebWorker()">Calulate Using Web Worker</button>
    <button onclick="alert('The page is running.')">Click Me</button>
    </body>
    </html>
  8. html5-webworker-example.js.
    // This function will handle the thread onmessage event when the web worker postMessage() function is invoked.
    onmessage = function(event){
    
        var result = 0;
    
        // get the post data from the event object.
        var numberInt = event.data;
    
    
        var startTime = new Date().getTime();
    
        // calculate the value.
        for(var i=1; i<=numberInt; i++){
            
            result += i;
    
            // the below source code will confirm that the calculation script thread is running on the backend.
            //if(i % 1000000000 == 0){
    
            //    console.log(i);
            
            //}
        }
    
        var endTime = new Date().getTime();
    
        var deltaTime = (endTime - startTime)/1000;
    
        console.log('web worker calculate used time : ' + deltaTime + ' seconds.');
    
        var resultJSONObj = {time:deltaTime, result:result};
    
        var resultStr = JSON.stringify(resultJSONObj);
    
        // post the value back to the web worker object, then it will trigger the web worker object's onmessage event function defined in the html5-webworker-example.html.
        this.postMessage(resultStr);
    }
  9. Below is the demo video of this example.

3. How To Use Web Worker To Get And Show Current Time On Web Page Example.

  1. This example contains 2 source files also, html5-web-worker-display-time.html, html5-web-worker-display-time.js.
  2. You can input a second interval value ( such as n seconds ) and then click the button to let the worker thread calculate the current time every n seconds and return it.
  3. When the worker object gets the current time value, it will display it on the web page.
  4. html5-web-worker-display-time.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Html5 Using Web Worker To Show Current Time Example</title>
    <script>
    
    function getCurrentTime(){
    
        var worker = new Worker('html5-web-worker-display-time.js');
    
        worker.onmessage = function(event){
    
            var currTimeDiv = document.getElementById('currentTime');
    
            currTimeDiv.innerHTML = event.data;
        }
    
        var timeDuration = document.getElementById('timeDuration').value;
    
        worker.postMessage(timeDuration);
    }
        
    </script>
    <style>
        .block{
            display:block; 
            margin-top: 10px;
        }
    </style>
    </head>
    <body>
    <h3>Html5 Using Web Worker To Show Current Time Example.</h3>
    <div id="currentTime" class="block"></div>
    <div>Return current time every 
        <input type="text" id="timeDuration" />
        seconds. 
        <input type="button" onclick="getCurrentTime()" value="Get Current Time"/>
    </div>
    </body>
    </html>
  5. html5-web-worker-display-time.js.
    onmessage = function(event){
        
        // get the seconds duration.
        var interval = event.data * 1000;
    
        setInterval(function(){
    
            var currentDate = new Date();
    
            postMessage(currentDate);
    
        }, interval);
    }
  6. Below is the example demo video.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky