Skip to content

Javascript clicker game

I’ve recently got myself into making a clicker game in javascript, but as expected, I ran into a little problem.

When I have for example 5 coins per second, it goes a lot faster, like i have 20 or 30 coins per second. There isn’t a specific pattern to this, eg that it goes 2x faster or 3x faster, pretty random.

These are parts of code involving coins, any feedback would be appreciated

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)

}

Edit: Here is the entire code if it helps:

<!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>

Answer

You add add multiple intervals without cancelling the old one. So cancel the old one before you create a new one.

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)
}