That Web Workers are scripts that work in background and do not interrupt user interface scripts. Now create a Web page named webworkerspage.html that uses a worker script file, named worker.js show how to use Web Workers in a Web page.
////Create a Web page named webworkerspage.html///
<!doctype html>
<head>
<title>Web Workers Example</title>
</head>
<body style="background-color:gold;">
<h3>The highest prime number discoverd so far is :<OUTPUT id="result"></OUTPUT></h3>
<script>
var worker=new Worker('worker.js');
worker.onmessage=function(event){
document.getElementById('result').textContent=event.data;
};
</script>
</body>
</html>
////Create worker.jd file////
var n=1
search:white(true)
{
n+=1;
for(var i=2;i<=math.sqrt(n);i+=1)
if(n%1==0)
continue search;
//found a prime!
postMessage(n);
}
Here: A web page created to display the highest prime number. This prime number is calculated with the helps of a web worker script file, worker.js. The Worker() constructor creates a worker instance to communicate with the worker. The onmessage event handler allows the code to receive message from the worker. In worker.js a script code is searching a prime number and sends a message back to The Web page. This script uses the postMessage() method to post a message when a prime number is found.
////Create a Web page named webworkerspage.html///
<!doctype html>
<head>
<title>Web Workers Example</title>
</head>
<body style="background-color:gold;">
<h3>The highest prime number discoverd so far is :<OUTPUT id="result"></OUTPUT></h3>
<script>
var worker=new Worker('worker.js');
worker.onmessage=function(event){
document.getElementById('result').textContent=event.data;
};
</script>
</body>
</html>
////Create worker.jd file////
var n=1
search:white(true)
{
n+=1;
for(var i=2;i<=math.sqrt(n);i+=1)
if(n%1==0)
continue search;
//found a prime!
postMessage(n);
}
Here: A web page created to display the highest prime number. This prime number is calculated with the helps of a web worker script file, worker.js. The Worker() constructor creates a worker instance to communicate with the worker. The onmessage event handler allows the code to receive message from the worker. In worker.js a script code is searching a prime number and sends a message back to The Web page. This script uses the postMessage() method to post a message when a prime number is found.
No comments:
Post a Comment