web worker API实现js多线程

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</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();
发布了142 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_35958891/article/details/104995511