首页 > 解决方案 > setTimeout 正在返回一个不相关的小数

问题描述

我正在构建一个青蛙风格的游戏。当玩家到达棋盘顶部 (this.y == -25) 时,玩家位置会重置 (this.x // this.y),玩家得分会增加 (this.points++)。

最初是这样写的:

class Hero {
    constructor() {
        this.points = 0;
    }
}

if (this.y == -25) {
   this.points++;
   setTimeout(() => {
      this.x = 202;
      this.y = 390;
      pointCount.innerHTML = (this.points);
   }, 100);
}

这将 pointCount 增加了 7,所以我尝试通过编写来纠正它:

if (this.y == -25) {
   this.points++;
   setTimeout(() => {
      this.x = 202;
      this.y = 390;
      pointCount.innerHTML = (this.points / 7);
   }, 100);
}

但现在每隔一段时间(不是每次,似乎是随机的)它会将该点增加 0.85714。

有什么想法吗?

标签: javascript

解决方案


有时你的函数被调用 7 次,有时它被调用 6 次。将分数除以 7 不是一个可靠的解决方法。您可以设置一个标志以确保只调用一次评分代码。

let canScore = true;
if (this.y == -25 && canScore ) {
    canScore = false;
    this.points++;
    setTimeout(() => {
        this.x = 202;
        this.y = 390;
        pointCount.innerHTML = (this.points);
        canScore = true;
    }, 100);
}

推荐阅读