注释详细,不多解释!请看代码!!!
- 简单交互页面 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web worker 最小公倍数和最大共约数</title>
</head>
<style>
body {
font-family: "微软雅黑";
font-size: 14px;
}
.input-number,.result,.operate {
margin: 10px auto;
text-align: center;
}
.result {
width: 200px;
text-align: left;
}
</style>
<body>
<div class="input-number">
<label for="first">
第一个数:
</label>
<input type="number" id="first" name="first">
</div>
<div class="input-number">
<label for="second">
第二个数:
</label>
<input type="number" id="second" name="first">
</div>
<div class="operate">
<button id="calculate">计算</button>
</div>
<div class="result">
<p>最小公倍数:<span id="common_multiple"></span></p>
<p>最大共约数:<span id="common_divisor"></span></p>
</div>
<script src="main.js"></script>
</body>
</html>
- 主线程js文件 main.js
var worker = new Worker('multiple-divisor.js'),
calculateBtn = document.getElementById('calculate');
// 监听点击事件
calculateBtn.addEventListener('click', function () {
var first = document.getElementById('first').value,
second = document.getElementById('second').value;
// 向子线程发送参数
worker.postMessage({first: parseInt(first), second: parseInt(second)});
});
// 接收数据
worker.onmessage = function(e) {
document.getElementById('common_multiple').textContent = e.data.multiple;
document.getElementById('common_divisor').textContent = e.data.divisor;
}
- web worker线程js文件 multiple-divisor.js
// 接收主线程发过来的参数
onmessage = function (e) {
var first = e.data.first,
second = e.data.second;
calculate(first, second);
}
// 求最小公倍数和最大公约数
function calculate(a, b) {
var c_multiple = multiple(a, b),
c_divisor = divisor(a, b);
// 向主进程发送计算结果
postMessage({multiple: c_multiple, divisor: c_divisor});
}
// 求最小公倍数
function multiple(a, b) {
return a * b / divisor(a, b);
}
// 求最大共约数
function divisor(a, b) {
if( a % b == 0) {
return b;
} else {
return divisor(b, a % b);
}
}
注意:本实例需要在服务器上运行