Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make loop pause every 100ms for visual effect Javascript

I’m currently building a roulette game. To the simulate wheel spinning I’m use this code:

function getColor(item){
var x = document.getElementById(item);
return x.className;
}

function spin() {
  spinning = true;
  
  for (let i = 0; i < options.length; i++) {
  document.getElementById("wheel").style.backgroundColor = getColor(options[i]);
  document.getElementById("number").innerHTML = options[i];
  
  //sleep for 100ms
  
} 
  spinning = false;
}

It does what I need but it does it too fast so you can’t see every number go by. Is there a way to make the program sleep for 100ms every iteration. When I try to use setTimeout it doesn’t pause the code. I’ve looked around at other question but they all say to use the timeout and it doesn’t work for me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

setTimeout will actually work for you.

let spinning = false;

const options = [1, 2, 3, 4];

function getColor(item) {
  var x = document.getElementById(item);
  return x.className;
}

function spin() {
  spinning = true;
  const total = options.length;
  const delayMs = 100;
  for (let i = 0; i < total; i++) {
    setTimeout(() => {
      document.getElementById("wheel").style.backgroundColor = getColor(
        options[i]
      );
      document.getElementById("number").innerHTML = options[i];
    }, delayMs * i);
  }
  setTimeout(() => {
    spinning = false;
  }, total * delayMs);
}

spin();
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app">
      <div>
        <p id="1" class="red" />
        <p id="2" class="yellow" />
        <p id="3" class="orange" />
        <p id="4" class="blue" />
      </div>
      <div id="wheel">
        <div id="number"></div>
      </div>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading