How to add a number to a var every second

时间:2017-12-18 08:22:54

标签: javascript html

As a beginner in Javascript, I'm trying to make a clicker game. I don't know how to add a number to a var every second

Below is the code at the moment. I'm not sure how to make one of my "dank miners" automatically add coins every second to the player. Let's say there are two auto miners, then the player earns 4 coins per second. Also how to display how much the player is automatically making.

Thanks!

malloc
let borkCoins = 0;

let dankMiner = 0;

const earnBork = () => {
  borkCoins += 1;
  displayScreen();
};

const buydankMiner1 = () => {

  if (borkCoins >= 20) {
    dankMiner += 1;
    borkCoins -= 20;
    displayScreen();
  } else {
    alert("Insufficient funds!")
  }
};

const displayScreen = () => {
  document.getElementById("bork-coins").innerText =
    borkCoins;
  document.getElementById("dankMiner").innerText =
    dankMiner;
};

displayScreen();

2 个答案:

答案 0 :(得分:1)

You can use setInterval function and do something like this :

"A2"
let borkCoins = 0;
let dankMiner = 0;

const earnBork = () => {
  borkCoins += 1;
  displayScreen();
};

/* Code Added */
setInterval(earnBork, 1000);
/*--*/

const buydankMiner1 = () => {
  if (borkCoins >= 20) {
    dankMiner += 1;
    borkCoins -= 20;
    displayScreen();
  } else {
    alert("Insufficient funds!")
  }
};

const displayScreen = () => {
  document.getElementById("bork-coins").innerText =
    borkCoins;
  document.getElementById("dankMiner").innerText =
    dankMiner;
};

displayScreen();

答案 1 :(得分:0)

Add an interval that checks for the number of miners:

doProduce