A web worker is basically a javascript code that runs in the background. It does not effect the performance of the Page. Usually When we run some script in our html page the page do not response until the script finishes.
By using Web Workers you can do the other functionalities like clicking, entering data and other things on the page because web worker runs on the background.
for example:
for(var i=0;i<10000000;i++){
//some code here
}
This code will run until the for loop finishes, so it can make web page running slower or may be unresponsive. By using web worker you can use this script in the background that will not effect the speed of your web page.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startscript()">Start Web Worker</button>
<button onclick="endscript()">End Web Worker</button>
<br><br>
<script>
var a;
function startscript() {
if(typeof(Worker) !== "undefined") {
if(typeof(w) == "undefined") {
a = new Worker("demo_workers.js");
}
a.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}
function endscript() {
a.terminate();
a= undefined;
}
</script>
</body>
</html>
0 Comment(s)