web workers 实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
<script>

  //注意:在chrome浏览器中必须在服务器环境下运行 var w1 = new Worker('./web/test.js'); //创建线程 w1.postMessage('hi'); w1.onmessage = function(ev){ alert(ev.data); console.log(w1); w1.terminate(); //关闭线程 } alert('触发了'); </script> </html>
self.onmessage = function(ev){

    var a = 1;
    for(var i=0;i<10000;i++){
        a += i;
    }
    self.postMessage(a);

    self.close();  //关闭线程
}

 

posted @ 2018-05-08 09:23  阿弥陀佛么么哒!  阅读(197)  评论(0编辑  收藏  举报