Hello, world!

HTML 5 Web Workers HTML

In the HTML tutorial defines how HTML web worker can execute tasks in the web content to process JavaScript in the background. In this tutorial you will learn how to abort, reuse and other functions regarding web worker.



HTML5 Web Workers

HTML web worker can execute tasks in the web content to process JavaScript in the background, without interfering the performance of the user interface.
 
What is a Web Worker?
The web page happens to be unresponsive when operating scripts in an HTML web page until the script is completed.
The HTML5 web worker is running JavaScript in the background thread, apart of other scripts, but not interfering the performance of the web page.
You can keep on doing whatever you want: clicking, selecting things, and others though the web worker runs in the background.

Browser Support

These are the browsers that support Web Workers. The figures in the table identify the first browser version that fully supports it.
API Web Workers
Chrome 4.0
Internet Explorer 10.0
Firefox 3.5
Safari 4.0
Opera 11.5

HTML Web Workers Example

This following example builds a basic web worker that count numbers in the background:

HTML code example web workers example:

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Count</button>
<button onclick="stopWorker()">Stop Count</button>
<p><strong>Note:</strong> Use Internet Explorer 10 or latest versions that support Web Workers.</p>
<script>
var w;
function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry, Web Workers is not supported in your browser...";
    }
}
 
function stopWorker() {
    w.terminate();
    w = undefined;
}
</script>

HTML output web workers example:

Count numbers:

Note: Use Internet Explorer 10 or latest versions that support Web Workers.



Verify Web Worker Support
Make sure to verify first that web worker is supported by your browser before creating it:
if(typeof(Worker) !== "undefined") {
    // Yes! Your browser supports Web worker!
    // Some code.....
} else {
    // Sorry! Your browser doesn’t support Web Worker..
}
Build a Web Worker File
You can create web worker in an external JavaScript.
We can build a script that counts. The script is saved in the "sample_workers.js" file:
var n = 0;

function timedCount() {
    n = n + 1;
    postMessage(n);
    setTimeout("timedCount()",500);
}

timedCount();

In the example above, the postMessage() method is applied to send a message back to the HTML page, it the most vital part of the code.
Note: In general web workers are not used for such basic scripts, but for more CPU intensive tasks.

Build a Web Worker Object
Finally you have the web worker file, you are required to call it from an HTML web page.
The lines below verify if the worker is already present, if not - it builds a new web worker object and executes the code in "sample_workers.js":
 
if(typeof(e) == "undefined") {
    e = new Worker("sample_workers.js");
}

After that we can submit and accept messages from the web worker.
On the web worker insert an "onmessage" event listener.
     e.onmessage = function(event){
    document.getElementById("result").innerHTML = event.data;
};
Once the web worker sends a message, the code inside the event listener is processed.
The information from the web worker is saved in event.data.

Web Workers and the DOM

Web workers do not have access to the JavaScript window object, document object and parent object , for the reason that web workers are in external files.

Reusing Web Worker

After it has been terminated, and if you set the worker variable to undefined, you can use again the code:
e = undefined;

Aborting Web Worker

Once a web worker object is built, and though after the external script is completed, it will go on listening with messages, until it is discontinued.
Apply the terminate() method to discontinue or terminate a web worker, and free browser/computer resources: For instance, e.terminate();

Complete Web Worker Example Code

The Worker code in the .js file is already created. The following is the code for the HTML page:

HTML code example complete web worker example code:

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Count</button>
<button onclick="stopWorker()">Stop Count</button>
 
<p><strong>Note:</strong>Use Internet Explorer 10 or latest versions that support Web Workers.</p>
 
<script>
var e;
 
function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(e) == "undefined") {
            w = new Worker("sample_workers.js");
        }
        e.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry, Web Workers is not supported in your browser...";
    }
}
 
function stopWorker() {
    e.terminate();
    e = undefined;
}
</script>

HTML output complete web worker example code:

Count numbers:

Note:Use Internet Explorer 10 or latest versions that support Web Workers.