web worker 处理线程

  index.html:

       

<!DOCTYPE html>
<html>
<head>
    <title>webworker</title>
</head>
<body>
<input type="text" name="number" id="number"/>
<input type="submit" value="add" id="submit"/>
<div id="result"></div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"></script>
</html>

script.js: 主线程

/**
 * Created by keejun on 13-12-17.
 */
$(document).ready( function(){
        $("#submit").click(function(){
             var number=$("#number").val();
             if(number){
                 var worker = new Worker("js/maths.js");
                 worker.postMessage(number);
                 worker.onmessage=function(e){
                        if(e.data!=""){
                             var span=document.createElement("span");
                             span.innerHTML= e.data;
                             var br=document.createElement("br");
                             document.getElementById("result").appendChild(span);
                             document.getElementById("result").appendChild(br);
                     }
                     else{
                         console.log("no datas!");
                         return false;
                     }
                 }
                worker.onerror=function(e){
                        alert(e.message+":"+ e.lineNumber);
                        throw e;
                 }
             }
             else{
                 console.log("no numbers");
                 return false ;
             }
            }
        )
    }
)



注:script.js , maths.js,inner.js 在一个js文件下

maths.js:先计算所有的数之和,发送数据到其他子线程进行进一步处理。

/**
 * Created by keejun on 13-12-17.
 */
 onmessage=function(event){
        var data=event.data;
        var sum =0;
        for(var j= 0;j<data;j++){
              sum+=j;
         }
       var worker = new Worker("js/inner.js");
       var str;
       worker.onmessage=function(event){
           if(event.data==1){
                  str=1;
             }
          else{
                  str=0;
              }
      }
     worker.postMessage(sum);
     postMessage(str);
 }



inner.js: 判断是否被3整除

/**
 * Created by keejun on 13-12-17.
 */
 onmessage=function(event){
         var data=event.data;
         var flag;
         if(data%3==0){
               flag=1;
          }
         else{
               flag=0;
          }
         postMessage(flag);
 }

     

  测试在Firefox可通过,由于chrome 在应对html5 web 嵌套 web worker存在bug。

     相关资料:https://code.google.com/p/chromium/issues/detail?id=31666  

                  http://stackoverflow.com/questions/9259251/unable-to-create-web-worker-from-inside-webworker-in-chrome

  


你可能感兴趣的:(web worker 处理线程)