Ads Top

What is web worker

A web worker is javascript when web page loading then scripts running in the background. Now page loaded and you can click or use any event because web worker working in the background. You can call the script with a script as an example. Web worker example below: 

webworkefile.js:

var counter = '';
function strtCouter(){
    console.log(counter);
    counter++;
    postMessage(counter);
    setTimeout(strtCouter, 1000);
}
strtCouter();

<script>
   var wwss = new Worker("webworkefile.js");
   wwss.onmessage = function(e){
   //console.log(e.data);
       document.getElementById('mainId').innerHTML = e.data;
    }
   function stop(){
       wwss.terminate();
    }
 </script>

The result will be increasing counter ++: 1

It will use on the body of HTML.

<div id="mainId"></div>
<button onclick="stop()">stop</button>

Your web worker will be work with the server. If you will not use any server then the result will not found an error showing this type:

“Uncaught DOMException: Failed to construct 'Worker': Script at”
“cannot be accessed from origin 'null'.  at”
So use live server extension in the VS Code. Then it’s the result will get as in the above example.

No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.