web worker API实现js多线程


<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Documenttitle>
head>
<body>
	<p>计数:<span id="data">span>p>
<button onclick="start()">开始button>
<button onclick="stop()">结束button>
<input type="text" value=""/>
<script>
var w;
function start () {
      
    if (typeof(w) === "undefined") {
      
      w = new Worker("1.js");
    }
    w.onmessage = function (event) {
      
      document.getElementById("data").innerHTML = event.data;
    };
}

function stop () {
      
  w.terminate();
  w=undefined;
}
script>
body>
html>

1.js部分

var i=0;

function timedCount()
{
     
    i=i+1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();

你可能感兴趣的:(js)