Reputation: 4306
I have a very simple code that generates a table.
However, when i added 3 if lines, it became super slow. Anyone have any ideas why?
Code:
for (var i=0; i<=noofRows; i++){
var rg = genguid();
for (var j=1; j<=noofbackuprows; j++){
to+='<tr>';
to+='<td>' + prefix + rg + '-' + j;
to+='</td>';
if (j<3){var vval = 10000};
if (j=3){var vval = 5000};
if (j>4){var vval = 2500};
to+='<td>' + vval + '</td>';
to+='</tr>';
}
}
Infringing lines:
if (j<3){var vval = 10000};
if (j=3){var vval = 5000};
if (j>4){var vval = 2500};
If i remove the infringing lines, it works great. What's going on?
Upvotes: 1
Views: 34
Reputation: 136154
The reason is because in the loop you're setting j=3
for evermore. I'm surprised this does not crash the browser entirely.
Use the equality operator ==
or strict equality operator ===
Upvotes: 1
Reputation: 128786
Two problems with what you currently have:
if (j<3){var vval = 10000};
if (j=3){var vval = 5000};
if (j>4){var vval = 2500};
Firstly, j = 3
assigns the value 3
to j
. It doesn't check to see whether j
is equal to 3
. To fix this, change this to ==
or ===
:
if (j === 3) { var vval = 5000; }
This is why your application is becoming slow, because your for
loop is getting stuck in a loop as after a certain point j
will always be equal to 3
.
Secondly, you should use else if
, otherwise all three if
statements will be checked even if the first one satisfied the requirement:
if (j < 3) { var vval = 10000 }
else if (j === 3) { var vval = 5000 }
else if (j > 4) { var vval = 2500 }
Also note that putting semicolons after the curly brackets on if
statements is unnecessary, so I've removed those as well.
Upvotes: 3