主體頁面:
<!DOCTYPE html />
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<!-- 單層嵌套 -->
<table id="table"></table>
<script type="text/javascript">
var worker = new Worker("worker1.js");
worker.postMessage("");
worker.onmessage = function (event) {
if (event.data != "") {
var j;
var k;
var tr;
var td;
var intArray = event.data.split(";");
var table = document.getElementById("table");
for (var i = 0; i < intArray.length; i++) {
j = parseInt(i / 10, 0);
k = i % 10;
if (k == 0) {
tr = document.createElement("tr");
tr.id = "tr" + j;
table.appendChild(tr);
}
else {
tr = document.getElementById("tr" + j);
}
td = document.createElement("td");
tr.appendChild(td);
td.innerHTML = intArray[j * 10 + k];
td.style.backgroundColor = "blue";
td.style.color = "white";
td.width = "30";
}
}
};
</script>
</body>
</html>
worker1.js
onmessage = function (event) {
var intArray = new Array(100);
for (var i = 0; i < 100; i++) {
intArray[i] = parseInt(Math.random() * 100);
}
var worker = new Worker("worker2.js");
//將隨機數提交給子線程進行挑選
worker.postMessage(JSON.stringify(intArray));
worker.onmessage = function (event) {
//向線程創建源發送消息
postMessage(event.data);
//關閉子線程
close();
}
};
worker2.js
onmessage = function (event) {
var returnStr = "";
var intArray = JSON.parse(event.data);
//篩選出3的倍數
for (var i = 0; i < intArray.length; i++) {
if (parseInt(intArray[i]) % 3 == 0) {
if (returnStr != "") {
returnStr += ";";
}
returnStr += intArray[i];
}
}
//向線程創建源發送消息
postMessage(returnStr);
//關閉子線程
close();
};