建议的重复项使用后端 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>
问题是,如果我在两台不同的计算机上的两个不同的浏览器中打开同一计时器,则计时器会关闭很多时间,有时长达一分钟。
如何确保所有设备上的计时器几乎相同/一致?