Jump to content

Why Does This FOR Loop Fail to Exit?


AARRGGHHH

Recommended Posts

I am rusty beyond words.  This is selecting a random color in hexadecimal.  Instead of selecting three colors  (like #FF8000)(orange) the loop never ends, and the page is never able to load.  It just keeps making that hex color code longer (#FF8080FCAD694897... etc...).  Apologies for the somewhat amateurish question. 

 				// Use random number to select primary and secondary colors 
				var color = Math.floor((Math.random() * 8) + 1); 
				if (color == 1) copy.style.stroke = "#FF0000";  // red 
				if (color == 2) copy.style.stroke = "#FF8000";  // orange 
				if (color == 3) copy.style.stroke = "#FFFF00";  // yellow 
				if (color == 4) copy.style.stroke = "#00FF00";  // green 
				if (color == 5) copy.style.stroke = "#0080FF";  // blue 
				if (color == 6) copy.style.stroke = "#FF00FF";  // purple 
				if (color == 7) copy.style.stroke = "#FFFFFF";  // white  	
			
				// Add some random colors. 
				var hexString = "#"; 
				if (color == 8) 
				{
					 // generate random  color 	 
					  var min = 128;
					  var max = 255;
					  var range = 1 + max - min;
					
						for (var getHEX = 1; getHEX = 3; getHEX++) 
						{
							var randomNumber = Math.floor(Math.random() * range + min);
							// Convert to hex
							randomNumber = randomNumber.toString(16);
							// Concatenate until I have a color for all three color channels  
                            hexString = hexString + randomNumber; 						
					  		// It should exit here. But it doesn't. It goes into an infinite loop creating an endless string of hex codes...
					  
                             };
			 		
						copy.style.stroke = hexString;  
				};

 

Link to comment
Share on other sites

You've mistakenly used the assignment operator "=" in the condition of your loop.

for (var getHEX = 1; getHEX = 3; getHEX++) 

In the condition, you're assigning 3 to getHEX which always evaluates to true, so the loop never ends.

Link to comment
Share on other sites

Did I mention "rusty"?

for (var getHEX = 1; getHEX < 4; getHEX++) 

Thank you so much, Ingolme.  If I hadn't already shaved my head, I would've been pulling my hair out over this one.   

Edited by AARRGGHHH
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...