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?
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
12times for days, and30times for months.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.