vue实现倒数的代码(纯编码)

原创
小哥 3年前 (2022-11-10) 阅读数 47 #大杂烩

本文将粘贴文章中的所有代码。

实现worker实现更准确的倒计时过程

代码部分我将直接在代码上。本文中的逻辑代码可以适当更改

// 处理worker发消息用
countDown.js

import Worker from ./count.worker;

const worker = new Worker();

// 初始化倒计时
export function initCount() {
  worker.postMessage({
    type: init,
    data: {},
  });
}

// 暂停时间
export function pauseTime(data) {
  worker.postMessage({
    type: pause,
    data,
  });
}

// 清除计时器
export function clearTimer() {
  worker.postMessage({
    type: clear,
    data: {},
  });
}

// 移除worker
export function removeWorker() {
  worker.terminate();
}

// 根据界面返回的时间校准检查的剩余时间。
export function alignTime(data) {
  worker.postMessage({
    type: align,
    data,
  });
}

// 开始倒计时
export function startCount (data) {
  worker.postMessage({
    type: start,
    data,
  });
}

// 获取worker
export function getWorker () {
  return worker;
}

// worker文件,内部worker线程执行我们的倒计时。
count.worker.js

const countObj = {
  // 存储settimeout
  timer: null,
  // 剩余倒计时时间
  examTime: -1,
  // 是否暂停倒计时的标识
  stopTimeStatus: false,
  setTimer(data) {
    this.timer = data;
  },
  setExamTime(data) {
    this.examTime = data;
  },
  setStopTimeStatus(data) {
    this.stopTimeStatus = data;
  },
};

function countDown() {
  if (countObj.timer) {
    return;
  }
  if (countObj.timer === 0) {
    postMessage([timeEnd, 0]);
    return;
  }
  // const start = new Date().getTime();
  countObj.timer = setTimeout(() => {
    countObj.timer = null;
    if (!countObj.getStopTimeStatus()) {
      countObj.setExamTime(countObj.getExamTime() - 1);
    }
    // const end = new Date().getTime();
    // console.log(误差, end - start);
    postMessage([countDown, countObj.getExamTime()]);
    countDown();
  }, 1000);
}

onmessage = function (e) {
  const {
    data: { type, data },
  } = e;
  switch (type) {
    case start:
      countObj.setExamTime(data);
      countDown();
      break;
    case align:
      countObj.setExamTime(data);
      postMessage([alignTime, data]);
      break;
    case pause:
      countObj.setStopTimeStatus(data);
      break;
    case init:
      countObj.setTimer(null);
      countObj.setExamTime(-1);
      countObj.setStopTimeStatus(false);
      break;
    case clear:
      clearTimeout(countObj.timer);
      countObj.setTimer(null);
      break;
    default:
      break;
  }
};

home.vue

import * as countDownInstance from ../utils/countDown;

mounted() {
      // 开始倒计时
      countDownInstance.startCount(this.examTime);
      const worker = countDownInstance.getWorker();
      worker.onmessage = async (event) => {
        const { data } = event;
        const [type, time] = data;
        if (type === countDown) {
          this.examTime = time;
        }
        if (type === timeEnd) {
          await this.autoSubmitPaper();
          this.$message.warning(时间结束时间);
          this.examTime = time;
        }
      };
}

那就别忘了找机会worker给终止掉, 使用worker.terminate

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门