Peter Christmas-Kjaer
Peter Christmas-Kjaer

Reputation: 13

Javascript function runs indefinitely when inside for-loop

On my page, I am adding <div> elements to the page using javascript. The content and number of 's comes from the content of a folder on the server. the page have a number of columns and I want to add each new to the smallest column. I created this function to determine what column is the smallest. When run/tested on a single request the function works as intended. when I call the function inside my "for-loop" with the elements that need to be added it runs indefinitely?

for for-loop is

for(i = 0; i < importedElement.length; i++){}

the function is

function findSmallestColumn() {
    var columns = document.getElementById("container").children;
    var columnsHeight = [];
    for (i = 0; i < numberOfColumns; i++) {
        columnsHeight[i] = columns[i].offsetHeight;
    }
    var min = Math.min(...columnsHeight);
    var minIndex = columnsHeight.indexOf(min) + 1;
    return minIndex;
}

*The "numberOfColumns is a var with a number attached.

Upvotes: 1

Views: 141

Answers (1)

bamtheboozle
bamtheboozle

Reputation: 6436

You have a second for loop inside your function, which infinitely increases i. Replace i with j or any other variable name in any of the two for loops and it will work as expected.

You could use the same variable name, i if you declare them locally inside the for loop using the let keyword, which declares variables only in the current block.

Upvotes: 3

Related Questions