// worker 定时器
const workerFunc = () => {
  self.onmessage = e => {
    const { delay } = e.data;
    self.setInterval(() => {
      self.postMessage(null);
    }, delay);
  };
};
const workerCode = workerFunc.toString();
const workerBlob = new Blob(
  [workerCode.slice(workerCode.indexOf("{") + 1, workerCode.lastIndexOf("}"))],
  { type: "text/javascript" }
);
const workerUrl = URL.createObjectURL(workerBlob);

// 定时器集合
const intervalWorkerMap = new Map<string, { worker: Worker; timer?: number }>();

export const createInterval = (func: () => void, delay = 0) => {
  const intervalId = Date.now().toString();
  const worker = new Worker(workerUrl);
  intervalWorkerMap.set(intervalId, { worker });

  // 如果worker报错，则使用window.setInterval
  const onerror = () => {
    worker.terminate();
    const timer = window.setInterval(() => {
      func();
    }, delay);
    intervalWorkerMap.set(intervalId, { worker, timer });
  };
  worker.onerror = onerror;
  worker.onmessageerror = onerror;

  worker.onmessage = () => func();
  worker.postMessage({ delay });

  return intervalId;
};

export const destroyInterval = (id: string) => {
  const { worker, timer } = intervalWorkerMap.get(id) || {};
  if (timer) {
    window.clearInterval(timer);
  } else if (worker) {
    worker.onmessage = null;
    worker.terminate();
  }

  intervalWorkerMap.delete(id);
};
