是否可以编写一个简单的专用网络工作者,以便它连续处理某些内容并仅在客户端询问时发送其状态。
到目前为止我所做的,客户端文件:
<script>
// spawn a worker
var worker = new Worker('basic-worker.js');
// decide what to do when the worker sends us a message
worker.onmessage = function(e){
document.getElementById('result').textContent = e.data;
};
</script>
<html>
<head></head>
<body>
<p>The Highest prime number discovered so far : <outpout id="result"></output></p>
</body>
</html>
工人档案:
var n = 0;
search: while (true) {
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime !
postMessage(n);
}
正如你所看到的,工人不断地发送它找到的素数。例如,当我单击客户端上的按钮时,我希望能够启动素数计算并要求工作人员发送他发现的最新素数。那将是这样的(我知道它不能正常工作,只能大致了解我想要什么):
工人档案:
var n = 0;
var lPrime = 0;
// post last prime number when receiving a message
onmessage = function(e) {
postMessage(lPrime);
}
// continously search for prime numbers
search: while (true) {
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime !
//postMessage(n);
lPrime = n;
}
客户档案:
<script>
// spawn a worker
var worker = new Worker('basic-worker.js');
// what to do when the worker sends us a message
worker.onmessage = function(e){
document.getElementById('result').textContent = e.data;
};
// post to the worker so the worker sends us the latest prime found
function askPrime(){
worker.postMessage();
};
</script>
<html>
<head></head>
<body>
<p>The Highest prime number discovered so far : <outpout id="result"></output></p>
<input type="button" onclick="askPrime();">
</body>
</html>