HTML5 Web Workers

By | February 6, 2020

A web worker is a JavaScript code that runs on a web page without affecting the user interface. Everyone wants that his website runs without interruption, his web page is fast, but in some major operation, the web page takes some time to give its response. If we use heavy javaScript then we need a heavy calculating browser for this and our web page becomes a bit slow for this, HTML5 provides us some easy way.

HTML5 provides us with a new technology called Web Workers. Through this technique the user can change the web page’s user interface without affecting the web page. Web workers need more space, it increases web site speed, it executes code on client side.

Browser Support:-

All modern browsers such as Firefox Chrome Opera Safari and Internet Explorer etc. support HTML5 web workers.

Create a Web Worker File:-

Create your own web worker in external JavaScript.

var i = 0;

function timedCount(){
     i = i + 1;
     postMessage(i);
     setTimeout("timedCount()",600);
}
timedCount();

Create a Web Worker Object:-

If we have a web worker file, then we need to call it in HTML5. For this we have a file test_workers.js.

if (typeof(a) == "undefined") {
               a = new Worker("test_workers.js");
          }

Now you can send and receive messages to web workers.

a.onmessage = function(event){
               document.getElementById("myId").innerHTML = event.data;
          };

Terminate a Web Worker:-

In this, we will tell you how to turn the worker on and off from the web page by clicking on the HTML button.

Web workers use terminate() method to eliminate free browser computer resources.

a.terminate();

Reuse the Web Worker:-

If your variable is undefined then after finishing it you can reuse the code.

a = undefined;

Full Web Worker Example Code:-


<body>

<p>Count Numbers: <output id="myId"></output></p>
<button onclick="startworker()">Start Worker</button>
<button onclick="stopworker()">Stop Worker</button>

<script>

var = a;

function startworker(){
     if (typeof(Worker) !== "undefined") {
          if (typeof(a) == "undefined") {
               a = new Worker("test_workers.js");
          }
          a.onmessage = function(event){
               document.getElementById("myId").innerHTML = event.data;
          };
     } else {
          document.getElementById("myId").innerHTML = "sorry your browser does not support web workers";
     }
}

function stopworker(){
     a.terminate();
     a = undefined;
}

</script>

</body>
Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *