Search This Blog

2023/04/21

Web Worker Process in HTML5

 A web worker is a JavaScript running in the background,

without affecting the performance of the page.


our HTML file create worker process ,which will run time consuming task
in background in
file bigLoop.js & return result by calling postMessage method

in Html file we get result passed by bigLoop.js in worker.onmessage in
event.data


HTML:
<html>
<head>
<title>Big for loop</title>
<script>
var worker = new Worker('bigLoop.js');
worker.onmessage = function (event) {
alert("Completed " + event.data + " iterations" );
worker.terminate()
};
function sayHello() {
alert("Hello sir...." );
}
</script>
</head>
<body>
<input type = "button" onclick = "sayHello();" value = "Say Hello"/>
</body>
</html>

BigLoop.js
for (var i = 0; i <= 1000000000; i += 1) {
var j = i;
}
postMessage(j);


When a web worker object is created, it will continue to listen for
messages (even after the external script is finished)
until it is terminated hence call terminate.

w.terminate();

No comments:

Post a Comment