Skip to content
Advertisement

Why does my page fall into the infinite loop?

function randomNumber(){
    var value;
    var flag = false;
    var tds = document.querySelectorAll('td');
    do{
        value = Math.round(Math.random() * (26 - 1) + 1);
        for(var t = 0; t < tds.length; t++){
            if(tds[t].innerHTML == value)
                flag = true;
        }
        if(!flag){
            return value;
        }
    }while(flag == true)
}

This function returns a random number for innerHTML of a new td. In case there are other tds with the same number as this code generates, the loop starts once again. If the generated number is unique, I add it to the innerHTML of a new td. But I can’t even load the page since I run into an infinite loop, but no matter how hard I tried, I couldn’t notice the problem in logic of this code.

Advertisement

Answer

As soon as your loop find the case where tds[t].innerHTML == value it sets flag to true – at this point you can never end the loop because nowhere do you check for a case where you can set flag to false, so your loop condition will always be true.

Here’s a similar example that illustrated this with an array. You can see that sometimes it adds numbers to the array (in the case where it finds a new value) but other times the loop hits 5000 iterations an exits (because it never finds a new value), in which case it adds undefined to the array, since the function hasn’t returned anything.

const arr = []
function randomNumber(){
    var value;
    var flag = false;
    var tds = arr
    var iterations = 0

    do {
        value = Math.round(Math.random() * (26 - 1) + 1);
        for(var t = 0; t < tds.length; t++){
            if(tds.includes(value))
                flag = true;
        }
        if(!flag){
            return value;
        }
        iterations += 1
        console.log(iterations)
    } while(flag == true && iterations < 5000)
}

for (let i = 0;i<20;i+=1) {
  arr.push(randomNumber())
}
console.log(arr)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement