-1

Im trying create some type of number generator on webpage. I want to show like five numbers before the generated number show. For better imagine, you can look to google generator. When you click generate, it shows like 3-4 numbers before generated number. I use setInterval or setTimeout but i dont know how it works. My js code:

var button = document.querySelector("button");

button.addEventListener("click",function() {
    for (var i = 0; i < 8; i++) {
        setInterval(textC,5);
    }
});

function textC(){
    number.textContent = Math.floor(Math.random() * 1000) + 1;
}

Thanks for every help!

2 Answers2

2

The issue with setInterval() is that it will continue forever unless cleared, causing you to keep generating random numbers. Instead you can use setTimeout(), but set the timeout to change based on the value of i in the for loop. That way, each interval will occur 50 m/s after the other.

See example below:

const button = document.querySelector("button");
const number = document.querySelector("#number");
button.addEventListener("click", function() {
  for (let i = 0; i < 5; i++) {
    setTimeout(textC, 50 * i);
  }
});

function textC() {
  number.textContent = Math.floor(Math.random() * 1000) + 1;
}
<p id="number"></p>
<button>Generate</button>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

Don't use a loop (why not?). Just nest setTimeout and call it until a predefined threshold is reached. It gives you maximum control.

var button = document.querySelector("button");
var number = document.querySelector("#number");
const nRuns = 12;
const timeout = 100;
let iterator = 0;

button.addEventListener( "click", textC);

function textC(){
    number.textContent = `${Math.floor(Math.random() * 1000) + 1}\n`;
    iterator += 1;
    if (iterator < nRuns) {
      setTimeout(textC, timeout)
    } else{
      iterator = 0;
      // you control the loop, so it's time for some extra text after it
      number.textContent += ` ... and that concludes this series of random numbers`;
    }
}
<p id="number"></p>
<button>Generate</button>
KooiInc
  • 119,216
  • 31
  • 141
  • 177