1

Im calling a for loop inside a for loop and its not working, here's the code :

function PopulateMonths() {
for (var m = 0; m < 12; m++) {
    var $month = $('.d-month').clone();
    $month.find('.d-header').text(m);
    $month = PopulateDays($month);
    $month.appendTo('#diary').show();
    $month = null;
}
}

function PopulateDays($month) {
for (var d = 0; d < 30; d++) {
    var $row = $('.d-row').clone();
    $row.find('.d-day').text(d);
    $row.appendTo($month).show();
    $row = null;
}
return $month;
}

If I call PopulateDays manually 12 times it works fine, as soon as I try to loop 12 times using PopulateMonths() the page crashes, CPU usage goes through the roof so im assuming a lot of work is going on.

What am I missing?

0

2 Answers 2

3

I've had to tackle a very similar issue before. It's because when you are cloning the element, you are also cloning their classes etc. And then you insert the cloned item into the document.

The next time you try to look for an element with that class, it will find two instances - the original one, and the one you cloned in the previous step. Both will be cloned again, and now you have 4 elements on the page. So you're basically doubling the number of elements on each iteration, and doing it 12 times for days, and 30 times for months.

2^12 = 4096
2^30 = 1,073,741,824

These are just rough estimates of how large it can grow. I haven't done any further analysis to find the exact numbers, but basically the exponential growth is eating up the CPU and crashing your browser.

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

2 Comments

I get you, So I need to be more specific with my selection, just getting my head round it. Thanks
Yeah, either be more specific, or remove the class from the cloned element based on which you are selecting.
0

I believe because you are cloning the set of month elements in this line:

var $month = $('.d-month').clone();

and then in the populate days function appending 30 rows to the month in this line:

$row.appendTo($month).show();

Then appending the month to the diary in this line:

$month.appendTo('#diary').show();

Then next time this line executes there is another month that get cloned in this line:

var $month = $('.d-month').clone();

As well as cloning the rows you just appended over again in this line:

var $row = $('.d-row').clone();

Executing this in a loop increases the load substantially.

Comments

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.