欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在angular中使用webWorker

程序员文章站 2022-03-26 18:06:58
...

1、html中webWorker

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>时间: <output id="result"></output></p>
<button onclick="startWorker()">开始工作</button>
<button onclick="stopWorker()">停止工作</button>

<p><strong>注意:</strong> Internet Explorer 9 及更早 IE 版本浏览器不支持 Web Workers.</p>
<script>
    let wk;
    function startWorker() {
        if(typeof(Worker) !== "undefined") {
            if(typeof(wk) == "undefined") {
                wk = new Worker("./static/clock-Worker.js");
            }
            wk.onmessage = function(event) {
                document.getElementById("result").innerHTML = event.data;
            };
        } else {
            document.getElementById("result").innerHTML = "抱歉,你的浏览器不支持 Web Workers...";
        }
    }

    function stopWorker()
    {
        wk.terminate();
        wk = undefined;
    }
</script>
</body>
</html>

clock-Worker.js

/// <reference lib="webworker" />
;(function () {
    const WEEK = {
        1: '周二',
        2: '周二',
        3: '周三',
        4: '周四',
        5: '周五',
        6: '周六',
        0: '周日',
    };
    // 返回月
    function getMonth(date) {
        const month = date.getMonth() + 1; // getMonth()得到的月份是0-11
        return setTimeFillZero(month);
    }
    // 返回天
    function getDay(date) {
        const day = date.getDate();
        return setTimeFillZero(day);
    }
    // 返回小时
    function getHours(date) {
        const hours = date.getHours();
        return setTimeFillZero(hours);
    }
    // 返回分
    function getMinutes(date) {
        const minute = date.getMinutes();
        return setTimeFillZero(minute);
    }

    // 返回秒
    function getSeconds(date) {
        const second = date.getSeconds();
        return setTimeFillZero(second);
    }
    // 返回拼接的日期
    const _getDate = ()=> {
        const _date = new Date();
        const year = _date.getFullYear();
        const month = getMonth(_date);
        const day = getDay(_date);
        const hours = getHours(_date);
        const minutes = getMinutes(_date);
        const seconds = getSeconds(_date);
        const week =  WEEK[_date.getDay()];
        return week + ' ' + year + '-' + month + '-' + day +  ' ' + hours + '-' +  minutes + '-' +  seconds;
    };

    /**
     * 数据填充
     * @param num 01 10 等格式化数据
     * @returns {string}
     */
    function setTimeFillZero(num) {
        return num < 10 ? '0' + num : num;
    }

    /**
     *
     * 设置时间
     */
    function getTime() {
        const time = _getDate();
        postMessage(time);
        setTimeout(getTime, 1000);
    }
    getTime();
})();

2、angular中使用webWorker

目前使用的是angular6,我是升级到angular8版本,具体请参考https://update.angular.io/#6.0:8.0

在angular中使用webWorker在angular中使用webWorker

根目录下创建 tsconfig.worker.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/worker",
    "lib": [
      "es6",
      "webworker"
    ],
    "types": []
  },
  "include": [
    "src/**/*.worker.ts"
  ]
}

tsconfig.app.json中exclude增加"**/*.worker.ts" 注意文件目录

在angular.json中 architect =》build =》options 增加 "webWorkerTsConfig": "tsconfig.worker.json",

在angularjson中 lint  =》options =》tsConfig 增加"tsconfig.worker.json"

private setTime() {
    /// <reference lib="webworker" />
    if (typeof Worker !== 'undefined') {
      // @ts-ignore
      this.interval = new Worker('./dynamic-clock.worker', { type: 'module' });
      this.interval.onmessage = ({ data }) => {
        this.time = data;
      };
      // worker.postMessage('hello');
    }else {
      const _week = this._getWeek();
      this.interval = setInterval(() => {
        this.time = _week + ' ' + AppUtil.timestampToTime(new Date(), 'yyyy-MM-dd HH:mm:ss');
      }, 1000);
    }
  }
dynamic-clock.worker.ts和clock-Worker.js一样