在angular中使用webWorker

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

根目錄下創建 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一樣

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章