javascript - 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。
有什么想法吗?
解决方案
有时你的函数被调用 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);
}
推荐阅读
- c++ - Qpaintevent和paintGL冲突
- google-app-engine - Gcloud deploy 未部署文件夹
- powershell - 禁止“尝试新的跨平台 PowerShell https://aka.ms/pscore6”
- jestjs - TypeError:intlProvider.getChildContext 不是函数
- linux - 根据 grep 响应为变量赋值
- python - For 循环在函数外工作正常,但在函数内抛出错误
- javascript - 重新检查“从谷歌表单下拉列表中删除所选项目”
- python-3.x - 无法将新的 groupby 数据框与原始数据框相关联
- bash - AWK 预读模式捕获
- javascript - 组合 2 个字符串时,Dom 元素显示的结果与静态输入查询不同