Web worker in long run brings the multithreading to the javascript. When executing any complex script in html page, the page became unresponsive . To solve this problem web-worker comes in action. In web workers we are creating new child thread.
Note : Actually we are creating the new child process and then a new thread gets spawned inside it
Web worker is script (another thread) running in the background without the main page needs to wait for it to gets completed
A user can still interact with the web page and web worker will run in the background.
Example :
<!DOCTYPE html>
<html>
<body>
<p>
The count is <span id=”showi”></span>
</p>
<p>
<button onclick=”startWorker()”>Start Worker</button><br>
<button onclick=”stopWorker()”>Stop Worker</button>
</p>
</body>
<script>
var w;
function startWorker(){
if(typeof(Worker) !== ‘undefined’)
{
if(typeof(w) == ‘undefined’)
{
w = new Worker(‘./web_worker.js’);
}
w.onmessage = function(event){
document.getElementById(‘showi’).innerHTML = event.data;
}
}
else
{
alert(‘Web worker not present’);
}
}
function stopWorker(){
w.terminate();
}
</script>
</html>
Now let us define web_worker.js file :
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout(“timedCount()”,500);
}
timedCount();
Problem of handling the complex script in web browser (main thread/thread for html browser)
Example :
Solution through web workers
We can use web worker. In this we can assign the complex calculation task to web worker thread
Example
index.html (Inside this html we will create the web worker object)
By Pankaj Kumar Agarwal