0

The suggested duplicate uses a backend NodeJS solution. I'm after a purely frontend solution.

I have this simple timer in Vue that uses a fixed timestamp as the end date.

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>

The problem is that if I open this same timer in two different browsers on two different computers, the timers are off by quite a bit... sometimes up to a minute.

How can I make sure timers are near identical/consistent across all devices?

ProEvilz
  • 5,310
  • 9
  • 44
  • 74
  • Your issue is probably due to using a non ISO standard date string format. Other possible issues could be different OS time settings – charlietfl Nov 19 '18 at 22:40
  • So what is your solution? – ProEvilz Nov 20 '18 at 01:53
  • Did you try valid date string or Date constructor? And define "quite a bit off" in more absolute terms – charlietfl Nov 20 '18 at 02:01
  • @charlietfl Depends on which device you compare the timers between. On one Windows laptop it's off by around 50 seconds yet both use the same initial timestamp to count down from. And I figure the date string / timestamp is valid? – ProEvilz Nov 20 '18 at 19:20

0 Answers0