zoukankan      html  css  js  c++  java
  • web worker的了解

    如,MDN文档中介绍的那样,使用demo如下

    <!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>webworker-demo</title>
    </head>

    <body>
    <input id="first" type="text" />
    <br />
    <input type="text" id="second">
    </body>
    <script>
    var myWorker = new Worker('worker.js');
    first.onchange = function () {
    // myWorker.terminate();
    myWorker.postMessage([first.value, 2]);
    console.time();
    console.log('Message posted to worker');
    }

    second.onchange = function () {
    // myWorker.terminate();
    console.time();
    myWorker.postMessage([first.value, second.value]);
    console.log('Message posted to worker');
    }
    myWorker.onmessage = function (e) {
    // result.textContent = e.data;
    console.log('Message received from worker');
    console.log(e.data)
    console.timeEnd();
    }
    </script>
    </html>
    worker.js,为了模拟计算过程的耗时,使用代码如下:
    onmessage = function (e) {
    console.log('Message received from main script');
    var workerResult = (e.data[0] * e.data[1]);
    var now = Date.now();
    while (Date.now() - now < 5 * 1000) {
    //延迟五秒
    }
    console.log('Posting message back to main script');
    postMessage(workerResult);
    }
    总结:我们可以把计算过程负责耗时的操作放入worker的线程中。让这个worker线程去计算,这样就计算过程中就不会卡住js线程的异步任务队列正常运行。new Worker(url), 操作时浏览器会去加载这个URL地址指向的js。
     
    待续...
  • 相关阅读:
    学会读懂 MySql 的慢查询日志
    Azure Mobile App
    ZOJ 3810 A Volcanic Island (2014年牡丹江赛区网络赛B题)
    学习日记之观察者模式
    Linux C高级编程——网络编程基础(1)
    Atitit.ati&#160;&#160;str&#160;&#160;字符串增强api
    ListView 自己定义BaseAdapter实现单选打勾(无漏洞)
    TintTo和TintBy
    cc.Sprite
    手机网页一行中文字数上限
  • 原文地址:https://www.cnblogs.com/www-wwr/p/9018810.html
Copyright © 2011-2022 走看看