javascript - 如何在没有后端的情况下同步 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>
问题是,如果我在两台不同计算机上的两个不同浏览器中打开同一个计时器,计时器就会关闭很多......有时长达一分钟。
如何确保所有设备上的计时器几乎相同/一致?
解决方案
推荐阅读
- mysql - 选择列的百分比
- reactjs - 单击带有路由的按钮后显示当前页面
- mysql - 无法在 MySQL 中安排事件
- openlayers - Openlayers 上带有 WebGL PointsLayer 的多个过滤器
- android - Android SDK 29 中的 Proguard 和使用者 proguard 的问题
- c# - 如何正确使用池连接?
- python - Selenium - 如何获取鼠标位置
- flutter - 无法使用 TextFormField 更新文本
- javascript - 服务器在页面刷新时返回旧数据,而在数据库中它们已更新
- java - JDBC中ResultSet对象的getString()方法返回一个尾部空格过多的字符串值