位置:首頁 > 軟件操作教程 > 編程開發(fā) > HTML > 問題詳情

HTML5 與Web Workers通信

提問人:劉團圓發(fā)布時間:2020-11-17

Web Workers生成以后,就可以使用postMessage API傳送和接收數(shù)據(jù)了。postMessage還支持跨框架和跨窗口通信。下面將通過一個實例來汫解如何與Web Workers通信。

△【例題】與Web Workers通信

代碼如下:

<!DOCTYPE html>  

<html>  

<head>  

<meta charset="UTF-8">  

<title>Insert title here</title>  

</head>  

<body>  

    <p>計數(shù)結(jié)果:<output id="result"></output></p>  

    <button onclick="start()">開始worker</button>  

    <button onclick="stop()">停止worker</button>    

    <script type="text/javascript">  

       var w;         

       function start(){  

           if(typeof(Worker)!="undefined"){

               if(typeof(w)=="undefined"){      

                   w = new Worker("webworker.js");

               }  

               w.onmessage = function(e){ 

                   document.getElementById("result").innerHTML=e.data;  

               };  

           }else{  

               document.getElementById("result").innerHTML="sorry,your browser does not support web workers";  

           }  

       }    

       function stop(){  

          w.terminate();

          w=undefined;  

       }  

    </script>  

</body>  

</html> 

image.png

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部