//worker.js
var i=0;
var buffer=[];
//接收消息 接收缓存区
setInterval(function(){
i++;
if(buffer.length>120){
for(var j=0;j<10;j++){
buffer.shift();
}
}
buffer.push(i);
},1);
//发送消息 发送缓存区
var fps=0;
setInterval(function () {
if(fps<=20){
postMessage({
"type":"test",
"data":buffer.shift()
});
fps++;
}
},1);
onmessage=function (data) {
if(data.data=="ok"){
fps--;
}
}
//index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var prev=0;
var worker=new Worker('./worker.js');
worker.onmessage=function(data){
if(data.data.data==undefined){
data.data.data=0;
}
console.log("data:"+data.data.data);
console.log("sub:"+(data.data.data-prev));
prev=data.data.data;
slow()
}
function slow() {
var result=0;
for(var i=0;i<100000000;i++){
result+=i;
}
worker.postMessage("ok");
}
</script>
</body>
</html>