1

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.

1
  • 3
    You've forgotten the var (or let) on both definitions of i.. Commented Sep 28, 2017 at 11:08

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The reason is that variables in JavaScript are scoped to functions. The for-loop does not provide a new scope. It should work if you re-declare the variable i inside the function.
Thank you very much! So clear now but I have been staring me blind on this for hours.
This question is a good example of why you should always use strict mode, it will complain if you forget to declare a variable and save you those hours of frustration. Using a linter also helps a lot with this kind of bug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.