The Web Workers are introduced with the
URL of the JavaScript which contains the web worker executable code. The code is used to set the event listener and communicate with the script which is drawn from the main page as follows.
Syntax
[html]var worker = new Worker("bigLoop.js”);[/html]
Then it checks if JavaScript file is present, the browser will send a new thread. if application have multiple script files then user need to use
importScripts()
method to import those files which takes names of those files as arguments as follows.
[html]importScripts(“bigLoop.js”, "demo_workers.js");[/html]
Now A
postmessage( )
is used to start a web worker and which also used to establish the communication between the web worker and main page. User can access the message passed by web worker by using the
onmessage
method.
The code below demonstrates the
onmessage method as follows.
[html]<!DOCTYPE HTML>
<html>
<head>
<title>Big for loop</title>
<script>
var worker = new Worker('bigLoop.js');
worker.onmessage = function (event) {
alert("Completed " + event.data + "iterations" );
};
function sayHello(){
alert("Hello sir...." );
}
</script>
</head>
<body>
<input type="button" onclick="sayHello();" value="Say Hello"/>
</body>
</html>
[/html]
Result
By running the above code in a preferred browser following output appears.
Now click on
Say Hello button then a dialogue box appears a shown below.
Now click on
OK button then user will get dialogue box with alert message as shown below.
The code below is used to demonstrate the JavaScript external file assigned by the web workers named as
"demo_workers.js"
as shown below.
[html]var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
[/html]
Web workers are stopped by themselves in order to stop the web worker by using
terminate()
method as shown below.
[html]
worker.terminate()
[/html]