Home > Mobile >  While loop not stoping with random number
While loop not stoping with random number

Time:10-22

i'm trying to generate random number between 0 and 10, but loop is not stops when it came to 10

function testNumber () {

    let i = (Math.floor(Math.random() * 10) 1)

    while (i < 10) {
        setInterval(() => {
            document.write("Random number: "   (Math.floor(Math.random() * 10) 1)
            )},1000)
           
             return i;
        
    }

    }

function test () {
    testNumber();

CodePudding user response:

I'm not sure I understood your question, but if I did, you want to keep generating random numbers less or equal to 10, until you get 10 and show them in HTML. This is the solution for that:

HTML:

<div > </div>

JS:

const num = document.querySelector('.num');

function testNumber () {
   let i = (Math.floor(Math.random() * 11)

    while (i !== 10) {
       num.innerHTML = `${num.innerHTML}Random number: ${i}<br>`
       i = (Math.floor(Math.random() * 11)
    }
}

CodePudding user response:

If you want to "stop generating random numbers when you get 10", you'll probably want something like this:

function testNumber() {

    let counter = 0

    while (counter < 10) {
        setInterval(() => {
            document.write("Random number: "   (Math.floor(Math.random() * 11))
            )},1000)
           
             counter  ;
    }
}

testNumber();

Your loop condition is currently your random number, that's why it will run until the number is 10 by chance. You need to initialize a separate counter variable which gets incremented in each iteration of your loop.

Also your current calculation Math.floor(Math.random() * 10) 1 would only return numbers from 1 to 10 (excluding 0).

And read about the setInterval function. I'm not sure if that's what you actually want to achieve.

CodePudding user response:

I think you never change i in loop. this works:

function testNumber () {
    let i=(Math.floor(Math.random() * 10) 1)
    const interval=
        setInterval( () => {
            i=(Math.floor(Math.random() * 10) 1)
            document.write("Random number: "  i.toString())
            if(i==10) clearInterval(interval)},1000)
}

function test () {
    testNumber()
}
test()

clearInterval(interval) allows you to exit interval.

  • Related