Search code examples
javascriptsettimeoutwaitsleep

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.


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>