前端效能最佳化:使用 Web Workers 實現輪詢

孙凯亮發表於2024-06-27
// pollWorker.js
import { Base64 } from 'js-base64';
import RsaAndAes from '~/composables/RsaAndAes';
import { getRandomNumberFn } from '~/composables/baseRequest';

export function createWorker() {
  const blob = new Blob(
    [
      `
let requestCount = 0;
// 處理收到的訊息
self.onmessage = function (event) {
  if (event.data.type === "start") {
    // 開始輪詢
    const interval = event.data.interval;
    startPolling(interval, event.data.url, event.data.data, event.data.headers);
  }
};

// 開始輪詢函式
function startPolling(interval, url, data, headers) {
  function poll() {
    fetch(url, {
      method: "POST",
      headers: new Headers(headers),
      body: JSON.stringify({ ...data }),
    })
      .then((response) => {
        return response.json();
      })
      .then((res) => {
        // 將請求結果傳送回主執行緒
        self.postMessage({ res, requestCount: requestCount++ });
      })
      .catch((error) => {
        console.log("Request failed:", error);
      });

    // 呼叫自身以實現持續輪詢
    setTimeout(poll, interval);
  }

  // 立即執行一次
  poll();
}
    `
    ],
    { type: 'application/javascript' }
  );

  const worker = new Worker(URL.createObjectURL(blob));
  // 將post函式傳遞給WebWorker

  const TOKEN = '';
  const saveData = JSON.parse(JSON.stringify({} || {}));
  const config = {};
  const interDomainName = '';
  const ENV = '';
  const nodeEnv = ''; 
  const Key = ''; //儲存公鑰

  // 傳送開始訊息給WebWorker,傳遞輪詢間隔
  worker.postMessage({
    type: 'start',
    interval: 5000,
    url: 'http://192.168.110.145:18200/gateway/xxxxxxx',
    headers: {
      'content-type': 'application/json; charset=utf-8',
      partnerId: 'MTAy',
      time: '',
      accountId: '',
      countries: '',
      authToken: TOKEN,
      requestId: ''
    },
    data: {
      secretCode: RsaAndAes.encrypt(Key),
      encryptedData: RsaAndAes.encryptAes(saveData)
    }
  }); // 每5秒輪詢一次
  return worker;
}

相關文章