为什么这个javascript函数每秒执行的次数比预期的要多

fykwrbwg  于 2023-01-08  发布在  Java
关注(0)|答案(1)|浏览(89)

我正在开发一种点击器游戏,用户可以购买升级。一个这样的升级涉及到用户每秒赚取一定数量的游戏内货币,在本例中为0.1。不幸的是,如果用户决定购买不止一个这样的升级,它似乎呈指数上升。我觉得这可能是因为setInterval()函数是每次都叠加,所以第一次是0.1,然后下一次是0.1 + 0.2,所以是0.3,然后是0.3 + 0.2 + 0.1,所以是0.6,依此类推。

upgradePerSec1.onclick = function() {
  if (presents >= cost1) {
    presents -= cost1;
    upgrade1Amount += 1;
    totalPresentsSpent += cost1;
    cost1 = Math.ceil(cost1Base *= 1.03 ** upgrade1Amount);
    perSec += 0.1;
    displayScore.innerHTML = format(presents) + " Presents delivered.";
    cost1Disp.innerHTML = "<hr>Cost: " + format(cost1);
    title.innerHTML = format(presents) + " Presents";
    perSecDisp.innerHTML = formatPerSec(perSec) + " presents /s";
    totalPresentsSpentDisp.innerHTML = format(totalPresentsSpent) + " Total presents spent";
    setInterval(increment1, 1000);
  } else {
    alert("You don't have enough presents! Still need: " + format(cost1 - presents));
  }
}

function increment1() {
  presents += perSec;
  totalPresents += perSec;
  displayScore.innerHTML = format(presents) + " Presents delivered.";
  totalPresentsDisp.innerHTML = format(totalPresents) + " Total presents delivered";
  title.innerHTML = format(presents) + " Presents";
}

下面是对这段代码的一些说明:

  • upgradePerSec1 = HTML按钮元素
  • cost1 =此升级的成本
  • perSec =存储每秒“礼物”数量的变量
  • displayScore = HTML标签元素
  • cost1Disp = HTML标签元素
  • title =浏览器选项卡标题
  • format() =通过添加逗号来设置大数格式的函数
  • totalPresents =未扣除成本的总呈现(用于统计部分)

我试过用数字替换perSec变量(显然不起作用)我试过让计时也上升,但无法得到正确的计时。我也在网上搜索了很多地方,但没有找到任何有用的结果。我在stack overlfow上看到一个,但它不适用于我。

gstyhher

gstyhher1#

你是对的,setInterval调用是堆叠的。要解决这个问题,你应该确保你只调用setInterval()一次(例如,通过在该行之前添加一个if语句来检查是否为perSec === 0)。
例如:

upgradePerSec1.onclick = function() {
  if (presents >= cost1) {
    if (perSec === 0) {
      setInterval(increment1, 1000);
    }
    presents -= cost1;
    upgrade1Amount += 1;
    totalPresentsSpent += cost1;
    cost1 = Math.ceil(cost1Base *= 1.03 ** upgrade1Amount);
    perSec += 0.1;
    displayScore.innerHTML = format(presents) + " Presents delivered.";
    cost1Disp.innerHTML = "<hr>Cost: " + format(cost1);
    title.innerHTML = format(presents) + " Presents";
    perSecDisp.innerHTML = formatPerSec(perSec) + " presents /s";
    totalPresentsSpentDisp.innerHTML = format(totalPresentsSpent) + " Total presents spent";
  } else {
    alert("You don't have enough presents! Still need: " + format(cost1 - presents));
  }
}

function increment1() {
  presents += perSec;
  totalPresents += perSec;
  displayScore.innerHTML = format(presents) + " Presents delivered.";
  totalPresentsDisp.innerHTML = format(totalPresents) + " Total presents delivered";
  title.innerHTML = format(presents) + " Presents";
}

相关问题