Home > Mobile >  How do I display the result of each random number in each iteration of the loop in javascript?
How do I display the result of each random number in each iteration of the loop in javascript?

Time:10-06

I tried with setIntervar it only showed each completed for loop but not each iteration. I have to see the three numbers that are thrown, for example, in the first iteration and show them in their respective container and so on until reaching twenty.

function generateNumber() {
  /* console.count(); */
  count = 0;
  for (var i = 0; i <= 20; i  ) {
    let n = document.getElementById("demo").innerHTML = Math.floor(Math.random() * 5);
    let n1 = document.getElementById("demo1").innerHTML = Math.floor(Math.random() * 5);
    let n2 = document.getElementById("demo2").innerHTML = Math.floor(Math.random() * 5);

    if (n === n1 && n1 === n2) {
      count  ;
      let audio = new Audio(
        "media/008868268_prev.mp3"
      );
      audio.play();
    } else
    if (n === n1 || n1 === n2 || n === n2 || n2 === n1 || n1 === n) {
      count  ;
    }
    document.getElementById("coinci").innerHTML = count;
  }
}
<div >
  <div id="demo"></div>
  <div id="demo1"></div>
  <div id="demo2"></div>
  <div id="coinci"></div>
</div>

<div >
  <button type="button" onclick="generateNumber()">Generar</button>
</div>

CodePudding user response:

If you want to delay iterations of a for loop you can use asynchronous functions. Here is a simple workaround for that. I defined a promise which will resolve after 100ms using setTimeout and in each iteration it awaits for the response of the promise.

let myDelay = () => new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve('delayed')
    }, 100)
})

let audio = new Audio(
    "media/008868268_prev.mp3"
);

async function generateNumber() {
    count = 0;

    for (var i = 0; i <= 20; i  ) {
        let delay = await myDelay()
        let n = document.getElementById("demo").innerHTML = Math.floor(Math.random() * 5);
        let n1 = document.getElementById("demo1").innerHTML = Math.floor(Math.random() * 5);
        let n2 = document.getElementById("demo2").innerHTML = Math.floor(Math.random() * 5);
        if (n === n1 && n1 === n2) {
            count  ;
            audio.play();
        } else if (n === n1 || n1 === n2 || n === n2 || n2 === n1 || n1 === n) {
            count  ;
        }
        document.getElementById("coinci").innerHTML = count;
    }
}
<div >
    <div id="demo"></div>
    <div id="demo1"></div>
    <div id="demo2"></div>
    <div id="coinci"></div>
</div>

<div >
    <button type="button" onclick="generateNumber()">Generar</button>
</div>

  • Related