我需要跟踪我在Angular (9)中为多个玩家制作的游戏的时间,所以我为打开的应用程序的每个实例运行计时器。由于某种原因,并不是所有的实例都同时完成。它们都是一起开始的,但其中一些明显比其他的快。我认为我下面使用的代码指定了一个间隔的时间量,但它是不一致的。
startRound() {
this.roundIntervalId = setInterval(() => {
this.timeLeft--;
}, 1000);
}
在大约30秒的时间内,一些计时器比其他计时器提前5秒结束,即使它们彼此都在1秒内开始。
我需要一个角度的解决方案,因为我使用的后端不能运行计时器。有什么想法吗?
谢谢!
发布于 2020-07-02 14:44:49
您还可以添加日期时间的检查。如下所示:
startRound() {
const startTime = new Date();
this.roundIntervalId = setInterval(() => {
this.timeLeft--;
if ((new Date() - startTime) / 1000) > 30 {
clearInterval(this.roundIntervalId);
}
}, 1000);
}
发布于 2020-07-02 15:08:08
如果您想将setInterval用作计时器,那么使用它是不可靠的,因为它取决于它内部的代码执行的时间,而这不是一个恒定的时间。我建议连续使用setTimeout,每个超时周期应计算为时钟的下一秒所需的时间。
例如:
// Please choose a static date and make it the same on every tab
var endTime = new Date(new Date().getTime() + 60000);
function loop() {
var timeLeft = Math.floor((endTime.getTime() - new Date().getTime()) / 1000);
console.log('Time left: ' + timeLeft);
if (timeLeft <= 0) {
console.log('Time up!');
return;
}
setTimeout(() => loop(), 1000 - new Date().getMilliseconds());
}
function startRound() {
// Wait till next second before starting
setTimeout(() => loop(), 1000 - new Date().getMilliseconds());
}
如果你在一秒的中间启动计时器,第一秒看起来会更短。因此,我们可能希望在启动计时器之前延迟到下一秒。
https://stackoverflow.com/questions/62690371
复制相似问题