首页 > 解决方案 > 如何在没有后端的情况下同步 JS 计时器?

问题描述

建议的副本使用后端NodeJS 解决方案。我追求纯粹的前端解决方案。

我在 Vue 中有一个简单的计时器,它使用固定的时间戳作为结束日期。

const V = new Vue({
  el: '#app',
  data: {
    endDate: null,
    timerInstance: null,
  },
  methods: {
    timer: function() {
      this.endDate = new Date("2018-11-20 03:30:00").getTime();
      const $this = this;
      const countDownDate = this.endDate;
      this.timerInstance = setInterval(function() {
        var now = new Date().getTime();
        var distance = countDownDate - now;
        var hours = Math.floor(
          (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        );
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        document.getElementById('timer').innerHTML = `Hours: ${hours}<br> Mins: ${minutes} <br> Seconds: ${seconds}`;
        if (hours <= 0 && minutes <= 0 && seconds < 1) {
          console.log("hit 0: ", seconds);
          // Stop the timer when it reaches 0
          clearInterval($this.timerInstance);
        }
      }, 1000);
    }
  },
  mounted: function() {
    this.timer();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div id="timer"></div>
</div>

问题是,如果我在两台不同计算机上的两个不同浏览器中打开同一个计时器,计时器就会关闭很多......有时长达一分钟。

如何确保所有设备上的计时器几乎相同/一致?

标签: javascriptvue.jstimer

解决方案


推荐阅读