LenPopLilly
LenPopLilly

Reputation: 1227

Nested loop in JavaScript/jQuery not working

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?

Upvotes: 1

Views: 263

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

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.

Upvotes: 0

Anurag
Anurag

Reputation: 141879

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.

Upvotes: 3

Related Questions