JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

Alex Franklin
Alex Franklin
10,112 Points

This code is freezing and then crashing my browser every single time...

I work in another text editor so that I can save each lesson to look back on for help. This code causes my browser / text editor to freeze immediately upon load, and then soon after will crash and close out... I have noticed this happening from time to time, but this is the first time I can't even interact with the page b/c it's frozen upon load...

Can someone please explain why this happens, what is wrong with my code, and how to avoid this happening going forward? Thanks!

<code><pre>

var html = ' '; var rgbColor;

function randomRGB() { return Math.floor(Math.random() * 256 ); }

function randomColor() { var color = "rgb("; color += randomRGB() + ','; color += randomRGB() + ','; color += randomRGB() + ')'; return color; }

function print(message) { document.write(message); }

for ( var i = 0; i , 100; i+= 1) { rgbColor = randomColor(); html += '<div style="background-color:' + rgbColor + '"></div>'; }

print(html);

</pre></code>

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 23,332 Points

I am not the best person to consult on JavaScript questions, but I think the problem is with your loop condition.

It should be

for (var i=0; i<100; i+= 1) 
Alex Franklin
Alex Franklin
10,112 Points

Wow such a simple mistake can really do some damage... THANK YOU JEFF!