切換瀏覽器頁簽時倒計時不準確或閃跳問題的解決方案

背景說明

    我們在項目中經(jīng)常遇到定時器的使用舆绎,比如倒計時哟沫,當(dāng)我們切換瀏覽器頁面時,會發(fā)現(xiàn)倒計時不準確了或者 會有秒數(shù)從40 直接跳躍到30的場景,這是為什么呢压彭? 
    其實會出現(xiàn)這種情況是因為網(wǎng)頁失去焦點時,主瀏覽器對這些定時器的執(zhí)行頻率進行了限制辱匿,降低至每秒一次灶泵,這就導(dǎo)致了不準確的問題,如何解決呢补箍?

解決方案

    worker-timers解決了以上問題改执,它可以保證在非活動窗口下也保持原有頻率倒計時。它的核心思想在于將定時器任務(wù)交由Web Worker處理坑雅,而Web Worker不受瀏覽器窗口失焦點的節(jié)流限制辈挂,它能夠依然按照原有頻率執(zhí)行代碼,確保了任務(wù)的準時執(zhí)行裹粤。

應(yīng)用場景

    游戲邏輯計算终蒂、實時數(shù)據(jù)刷新、定時推送服務(wù)等遥诉,均能確保數(shù)據(jù)的準確性

倒計時案例

  1. 安裝 npm install worker-timers dayjs
  2. 公共方法utils
// utils.timer.js
import { clearTimeout, setTimeout } from 'worker-timers';
class Timer {
  timerList = [];

  addTimer (name, callback, time = 1000) {
    this.timerList.push({
      name,
      callback,
      time
    });
    this.runTimer(name);
  }
  static runTimer (name) {
    const _this = this;
    (function inner () {
      const task = _this.timerList.find((item) => {
        return item.name === name;
      });
      if (!task) return;
      task.t = setTimeout(() => {
        task.callback();
        clearTimeout(task.t);
        inner();
      }, task.time);
    })();
  }
  clearTimer (name) {
    const taskIndex = this.timerList.findIndex((item) => {
      return item.name === name;
    });
    if (taskIndex !== -1) {
      // 由于刪除該計時器時可能存在該計時器已經(jīng)入棧拇泣,所以要先清除掉,防止添加的時候重復(fù)計時
      clearTimeout(this.timerList[taskIndex].t);
      this.timerList.splice(taskIndex, 1);
    }
  }
}

export default new Timer();
  1. 封裝倒計時組件
// CountDown.vue 組件
<template>
  <div class="countdown">
    <slot name="time" :timeObject="timeObject"></slot>
    <div v-if="!$scopedSlots.time">
      <span class="letter" v-for="(letter, i) of display" :key="i">{{ letter }}</span>
    </div>
  </div>
</template>
<script>

import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import duration from 'dayjs/plugin/duration'
import timer from '@/utils/timer.js';

dayjs.extend(utc)
dayjs.extend(duration)
export default {
  name: 'CountDown',
  props: {
    time: { type: [Date, Number, dayjs], default: () => Date.now() }, // 開始時間
    end: { type: [Number, String, Date], required: true }, // 結(jié)束時間
    format: { type: String, default: 'HH : mm : ss' } // 格式
  },
  data () {
    return {
      now: 0,
      intervalId: Symbol('statTimer'),
      endTime: null,
      isPause: false // 暫停否
    }
  },
  computed: {
    duration () {
      return dayjs.duration(this.remain * 1000)
    },
    remain () {
      let number = ''
      this.endTime = this.endTime + ''
      if (this.now) {
        if (this.endTime.length == 10) {
          number = this.endTime - this.now <= 0 ? 0 : this.endTime - this.now
        } else if (this.endTime.length == 13) {
          number = this.endTime / 1000 - this.now <= 0 ? 0 : this.endTime / 1000 - this.now
        }
      }
      return number
    },
    months () { return this.duration.months() },
    weeks () { return this.duration.weeks() },
    days () { return this.duration.days() },
    hours () { return this.duration.hours() },
    minutes () { return this.duration.minutes() },
    seconds () { return this.duration.seconds() },
    count () { return this.remain >= 1 },
    years () { return this.duration.years() },
    display () { return this.duration.format(this.format) },
    timeObject () {
      if (this.months == 0 && this.weeks == 0 && this.days == 0 && this.hours == 0 && this.minutes == 0 && this.seconds == 0 && this.years == 0) {
        this.timeEnd()
      }
      return {
        formatTime: this.display, // 時間段
        months: this.fixedNumber(this.months),
        weeks: this.weeks,
        days: this.fixedNumber(this.days),
        hours: this.fixedNumber(this.hours),
        minutes: this.fixedNumber(this.minutes),
        seconds: this.fixedNumber(this.seconds),
        years: this.fixedNumber(this.years),
      }
    }
  },
  mounted () {

  },
  methods: {
    getTimeInfo () {
      return { ...this.timeObject, end: this.end, time: this.time }
    },
   // 恢復(fù)
    recover () {
      this.isPause = false
      timer.clearTimer(this.intervalId)
      timer.addTimer(this.intervalId, () => { this.now++ }, 1000)
      this.$emit('countDownCallback', { type: 'recover', value: this.getTimeInfo() })
    },
    // 暫停
    pause () {
      this.isPause = true
      timer.clearTimer(this.intervalId)
      this.$emit('countDownCallback', { type: 'pause', value: this.getTimeInfo() })
    },
    // 結(jié)束回調(diào)
    timeEnd () {
      this.$emit('countDownCallback', {
        type: 'timeEnd',
      })
    },
    // 補零
    fixedNumber (number) {
      number += ''
      return number.length == 2 ? number : '0' + number
    }
  },
  watch: {
    time: {
      immediate: true,
      handler (n) {
        if (n && !this.isPause) {
          this.now = this.time / 1000
        }
      }
    },
    end: {
      immediate: true,
      handler (n) {
        this.endTime = Number(n)
      }
    },
    count: {
      handler (v) {
        if (v) timer.addTimer(this.intervalId, () => { this.now++ }, 1000)
        else timer.clearTimer(this.intervalId)
      },
      immediate: true
    }
  },
  destroyed () { timer.clearTimer(this.intervalId) }
}
</script>
<style scoped>
.letter {
  display: inline-block;
  white-space: pre;
}
</style>
  1. 組件使用方法
<template>
  <div class=''>
    <countdown ref="countdown" @countDownCallback="countDownCallback" :end="endTime" :time="Date.now()" format="DD[天] HH[時]  mm[分] ss[秒]">
    <!-- <template #time="{ timeObject }">
        <div>
          {{ timeObject }}
        </div>
      </template> -->
    </countdown>
    <el-button @click="pause">暫停</el-button>
    <el-button @click="recover('continue')">恢復(fù)</el-button>
    <el-button @click="changeEnd">變更結(jié)束時間</el-button>

  </div>
</template>

<script>
import dayjs from 'dayjs'
import Countdown from './Countdown.vue'
export default {
  name: 'CountDownDemo',
  components: { Countdown },
  props: {},
  data () {
    return {
      dayjs,
      endTime: dayjs('2024-08-23 16:16:00').valueOf()
    }
  },
  methods: {
    changeEnd () {
      this.endTime = dayjs('2024-08-24 16:18:00').valueOf()
    },
    pause () {
      this.$refs.countdown.pause()
    },
    recover () {
      this.$refs.countdown.recover()
    },
    countDownCallback ({ type, value }) {
      console.log('value: ', value);
      console.log('type: ', type);
    }
  }
}
</script>
  1. 實際效果


    image.png

摘抄自:https://blog.csdn.net/gitblog_00561/article/details/141294756

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末矮锈,一起剝皮案震驚了整個濱河市霉翔,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌愕难,老刑警劉巖早龟,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件惫霸,死亡現(xiàn)場離奇詭異,居然都是意外死亡葱弟,警方通過查閱死者的電腦和手機壹店,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來芝加,“玉大人硅卢,你說我怎么就攤上這事〔卣龋” “怎么了将塑?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蝌麸。 經(jīng)常有香客問我点寥,道長,這世上最難降的妖魔是什么来吩? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任敢辩,我火速辦了婚禮,結(jié)果婚禮上弟疆,老公的妹妹穿的比我還像新娘戚长。我一直安慰自己,他們只是感情好怠苔,可當(dāng)我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布同廉。 她就那樣靜靜地躺著,像睡著了一般柑司。 火紅的嫁衣襯著肌膚如雪迫肖。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天帜羊,我揣著相機與錄音咒程,去河邊找鬼。 笑死讼育,一個胖子當(dāng)著我的面吹牛帐姻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播奶段,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼饥瓷,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了痹籍?” 一聲冷哼從身側(cè)響起呢铆,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蹲缠,沒想到半個月后棺克,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體悠垛,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年娜谊,在試婚紗的時候發(fā)現(xiàn)自己被綠了确买。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡纱皆,死狀恐怖湾趾,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情派草,我是刑警寧澤搀缠,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站近迁,受9級特大地震影響艺普,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鉴竭,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一衷敌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧拓瞪,春花似錦、人聲如沸助琐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽兵钮。三九已至蛆橡,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間掘譬,已是汗流浹背泰演。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留葱轩,地道東北人睦焕。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像靴拱,于是被迫代替她去往敵國和親垃喊。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容