html5之Web Workers示例
Web Workers使得html5也可以使用类似后台异步化、线程化的操作,让假死、卡不再存在,非常适合httpreqeust/io等操作。示例如下:
x.htm
<html>
<head>
<title>Web Workers</title>
</head>
<body>
<div class="page">
<div class="article">
<h2 class="topic"><strong id="result">正在计算Fibonacci(35)...,你可以先看看下面的介绍!</strong></h2>
</div>
</div>
</body>
<script type="text/javascript">
var wt = function(){
if(typeof Worker == 'undefined'){document.getElementById('result').innerHTML = '你正在使用的浏览器暂时还不支持WEB Workers!';return;}
var worker = new Worker("x.js");
worker.onmessage = function(event){
document.getElementById('result').innerHTML = event.data;
};
worker.onerror = function(event){
alert('Worker error:'+error.message+'\n');
throw error;
};
worker.postMessage('35');
};
wt();
</script>
</html>
x.js:
var fibonacci = function(n){
var rv = {'0':0,'1':1},l=0,r=0,i=0;
!function(n){
if(!(n in rv)){
l = rv[(n-1)]||arguments.callee(n-1);
r = rv[(n-2)]||arguments.callee(n-2);
rv[n] = l+r;
}
return rv[n];
}(n);
l = r = null;
return rv[n];
};
var fibonacci2 = function(n){
var i2 = 0;
var fb2 = function(n){
return n<2?n:arguments.callee(n-1)+arguments.callee(n-2);
};
return fb2(n);
};
var onmessage = function(event){
var n = parseInt(event.data,10);
postMessage(fibonacci2(n));
};