1

I am building a browser pet raising game. My plan is to use if/else to determine what the HP drop rate should be for the pet. If below a certain hunger / happiness, the HP will drop faster and faster.

I am using a variable setInterval, and the value inside is not update, but the value is updating when printing to the console.

let hp = 100;
let dropHPWeight = 6000;
let dropHPCall = setInterval(dropHP, dropHPWeight);

  function dropHP() {
    hp = (hp % 360) - 1;
    console.log(dropHPWeight);
    dropHPWeight = dropHPWeight + 6000;
  }

Here I am dropping the HP every 6 seconds, and then as a test, I am seeing if it will increase, but it does not.

Where am I going wrong here?

ETHan
  • 187
  • 1
  • 4
  • 17
  • What's "hp" here? And how will this go faster and faster if you keep adding time? And it's always the first interval's time if you only call "setInterval" once. – Dave Newton Jun 15 '20 at 20:56
  • `setInterval(dropHP, dropHPWeight)` does not store the actual variable, the `dropHPWaight` variable is being evaluated and it's value (6000) is being passed to `setInterval`. Raising the variable's value will not change the interval. – MrLumie Jun 15 '20 at 20:59
  • is there a way to update the variable? @MrLumie – ETHan Jun 15 '20 at 21:02
  • @DaveNewton My apologies. ill update post. HP = 100; – ETHan Jun 15 '20 at 21:02
  • Does this answer your question? [Changing the interval of SetInterval while it's running](https://stackoverflow.com/questions/1280263/changing-the-interval-of-setinterval-while-its-running) – Heretic Monkey Jun 15 '20 at 21:06
  • 1
    It's more likely Heritic's reference is what you're looking for, e.g., at the end of the timeout, call `setTimeout` again w/ the same method argument and the new time. Once a `setInterval` is started, it will always have the same interval (that's the point of it). – Dave Newton Jun 15 '20 at 22:13

1 Answers1

0

As some are mentioning in the comments, you cannot change the interval of a setInterval once it has been initiated. You are better off using setTimeout. Like this:

let hp = 100;
let dropHPWait = 6000;

function dropHP() {

  hp = (hp % 360) - 1;
  dropHPWeight = dropHPWait + 6000;

  if (somecondition){
    setTimeout(dropHP, dropHPWait)
  }

}

dropHP()

Now you call dropHP, which changes the interval, and then uses setTimeout to call itself again after the given increment. I stuck the setTimeout inside some conditional, because you don't want it to run forever (so you have to decide at what point you want it to stop running).

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78