我最近开始使用javascript制作点击游戏,但正如预期的那样,我遇到了一个小问题。
当我每秒有5个硬币时,速度会快得多,就像我每秒钟有20或30个硬币一样。对此没有特定的模式,例如它快2倍或快3倍,非常随机。
这些是涉及硬币的代码部分,任何反馈都将受到赞赏
var coinsPS = 0;
..................
setInterval(function renderCoinsPS() {
document.getElementById("coinsPS").innerHTML = "Coins per second: " + coinsPS;
})
....................
function getCoinsPS() {
if (coins >= 50) {
coinsPS += 10;
coins -= 50;
} else {
alert("Sorry, you don't have enough coins.")
}
........................
setInterval(function coinPS() {
coins += coinsPS;
}, 1000)
}
编辑:如果有帮助,这是整个代码:
<!DOCTYPE Html>
<head>
<title>Coin Clicker</title>
</head>
<body>
<h1>Coin Clicker</h1>
<h3 id="coins"></h3>
<h4 id="coinsPS"></h3>
<button onclick ="gainCoin()">Coin</button>
<button onclick ="getCoinsPS()">1 Coin Per Second</button>
<script>
var coins = 0;
var coinsPS = 0;
var coinsPC = 1;
function gainCoin() {
coins += coinsPC;
}
setInterval(function renderCoins() {
document.getElementById("coins").innerHTML = "Coins: " + coins;
})
setInterval(function renderCoinsPS() {
document.getElementById("coinsPS").innerHTML = "Coins per second: " +
coinsPS;
})
function getCoinsPS(){
if (coins >= 50){
coinsPS += 1;
coins -= 50;
}
else{
alert("Sorry, you don't have enough coins.")
}
setInterval(function coinPS(){
coins += coinsPS;
}, 1000)
}
</script>
</body>
答案 0 :(得分:1)
添加多个间隔而不取消旧间隔。所以在创建一个新的之前取消旧的。
var addInterval;
function getCoinsPS() {
if (coins >= 50) {
coinsPS += 10;
coins -= 50;
} else {
alert("Sorry, you don't have enough coins.")
}
if (addInterval) window.clearTimeout(addInterval)
addInterval = setInterval(function coinPS() {
coins += coinsPS;
}, 1000)
}