How to pause for 1 second in between the iterations of my loop

How do I pause for 1 second in between every iteration of my while loop without changing up anything but adding some code?

function getStone() {
    while (true) {
        let stoneChance = Math.floor(Math.random() * 10);
        if (stoneChance == 5) {
            stoneAmt++;
            document.getElementById("stone_count").innerHTML = stoneAmt;
        }
    }
}
getStone();

<itembox class="shadow">
 <div class="center top-bel">
   <img src="assets/img/ore/stone_ore.png" id="ore_icon" title="item" original width="60px" original-height="60px">
   </div>
    <div class="center desc-bel" id="stone_count">0</div>
</itembox>

Perhaps use a timeout?

If you wrap the code inside a setInterval you do not need the loop. The code will just run at every interval.

let stoneAmt = 0;

function getStone() {
  setInterval(() => {
    let stoneChance = Math.floor(Math.random() * 10);
    if (stoneChance == 5) {
      stoneAmt++;
      document.getElementById("stone_count").innerHTML = stoneAmt;
    }
  }, 1000);
}
getStone();
1 Like

I just made my function and when I run it I just did this

function getStone() {
    let stoneChance = Math.floor(Math.random() * 10);
    if (stoneChance == 5) {
        stoneAmt++;
        document.getElementById("stone_count").innerHTML = stoneAmt;
    }
}

setTimeout(getStone, 1000);

And it works just as well with less code. As SAid here

Seeing as you had a loop in the code, didn’t you want it to run continuously?

The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

But my code DOES run infinitly.

What Lasse is saying is that if you wanted to drop the while loop, you can do it with the setInterval method.

I know but I fixed it already.

No, it doesn’t. The function getStone runs one time after 1 second.

Edit: In reference to the latest code you posted.

it works perfectly on my web browser

This is where I put it chick on the buy pickaxe after you get 25 gold from clicking and waiting and you will see that it works perfectly fine
https://idle-hunt.netlify.app/

You are using setInterval on that site in the code, not setTimeout.

setInterval(getStone, 1000);
setInterval(getCopper, 1000);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.