Explain, How to perform heavy task in the background using HTML5 and JavaScript?

0 votes
202 views
Rahul Ahuja asked 17-Nov-2018 in programming by Rahul Ahuja

Explain, how to perform heavy task in the background using HTML5 and JavaScript?

1 Answer

0 votes
Arti Mishra answered 17-Nov-2018 by Arti Mishra

"Using WebWorker API"

HTML5 provides WebWorker API to perform JS operation on the background so that we can reduce the CPU time and work because some time JS create a web page as responsive due to the huge amount of work performed by CPU. 

In HTML "Worker" class is defined to perform JS operation on the background.

Explain, How to perform heavy task in the background using HTML5 and JavaScript?

.

Here is a simple example for performing the heavy task in the background.

 <html> <head> 

 <script>
 var w=null;
 function callWorker()
 {
 if(Worker)
 {
 w=new Worker("demo.js");
 w.onmessage=function(event)
 {
 document.getElementById("res").innerHTML=event.data;
 };
 }
 else
 document.write("Worker Not Supported.........");
 }

 function stopWorker()
 {
 if(Worker)
 {
 w.terminate();
 w=null;

 }

 }
 </script>
 </head>
 <body onLoad="callWorker();">
 <h1>Welcome User........</h1>
 <h1><div align="center"id="res"></div></h1>
 <input type="button" value="Start Worker"onClick="callWorker();">
 <input type="button" value="Stop Worker"onClick="stopWorker();">
 </body>
 </html>

Demo.js

var i=1;

function count()
{
 i=i+1;
 postMessage(i);
 alert("Hello....");
 setTimeout("count()",500);
}
count();




"Thanks!!! for Reading"