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
  }
}
4
  • I want to make this as simple as possible with ought changing a lot of code Commented Jun 29, 2020 at 14:05
  • use setInterval() to let a function run every x miliseconds. Use clearInterval to clear the interval if you don't need it anymore. Commented Jun 29, 2020 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 stackoverflow.com/questions/3583724, stackoverflow.com/questions/11764714 or stackoverflow.com/questions/27443185 Commented Jun 29, 2020 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. Commented Jun 29, 2020 at 14:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.