<!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();