html HTML5 Web Workers示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html HTML5 Web Workers示例相关的知识,希望对你有一定的参考价值。

var i=0;

function timedCount()
{
i=i+1;
postMessage(i);                   //posts a message back to the HTML page.
setTimeout("timedCount()",500);
}

timedCount();
<!-- When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. -->

<!-- A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting -->
<!-- the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., -->
<!-- while the web worker runs in the background. -->

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>
<br /><br />


<script>
var w;

function startWorker()
{
if(typeof(Worker)!=="undefined")            //check whether the user's browser supports it
  {
  w=new Worker("demo_workers.js");          //creates a new web worker object and runs the code in "demo_workers.js"

  //Add an "onmessage" event listener to the web worker
  //When the web worker posts a message, the code within the event listener is executed. The data from the web worker
  //is stored in event.data.
  w.onmessage = function (event) { document.getElementById("result").innerHTML=event.data; };
  }
else
  {
  document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
  }
}

function stopWorker()
{ 
w.terminate();         //terminate a web worker, and free browser/computer resources
}
</script>

</body>
</html>

以上是关于html HTML5 Web Workers示例的主要内容,如果未能解决你的问题,请参考以下文章

HTML5 Web Workers

Html5之高级-12 Web Workers(概述 API)

HTML5Web Workers

HTML5(四)——Web Workers

浅谈Web Workers

HTML5 Web Workers 运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。类似多线程并行处理