0

I am making a game in which the "player/user" will loose hunger. I want to make it so that when their hunger gets bellow 25 (var f) then their health (var h) will start to decrease by 20 every 5 seconds. But once the hunger goes up above 25, the health stops decreasing. This is why I am using a while event. I am not sure how to make it so the function waits five seconds, and then restarts.

function health() { 
h = 500; 
displayHealthCount();
while (f <= 25) {
  h -= 20;
displayHealthCount();
  //I want to make it so it waits for five seconds here
  }
}
Sophia
  • 1
  • 1
  • I want to make this as simple as possible with ought changing a lot of code – Sophia Jun 29 '20 at 14:05
  • use [setInterval()](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) to let a function run every x miliseconds. Use clearInterval to clear the interval if you don't need it anymore. – cloned Jun 29 '20 at 14:05
  • Please do a bit of research before asking something like this. Besides the already mentioned duplicate, typing something trivial such as “javascript wait in loop” into Google, would have also easily found https://stackoverflow.com/questions/3583724/, https://stackoverflow.com/questions/11764714/ or https://stackoverflow.com/questions/27443185/ – CBroe Jun 29 '20 at 14:09
  • setInterval is not the simplest solution here. Instead the solution with changing the smallest amount of code as the OP wanted would be to use async/await. You can make your function `async` and then do `await new Promise(resolve => setTimeout(resolve, 5000))` inside the loop. – CherryDT Jun 29 '20 at 14:11

0 Answers0