Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

'For Loop' problem

Status
Not open for further replies.

pob327

Technical User
Jul 19, 2007
13
0
0
US
I am trying to cycle through an array slowly, but my code seems to execute then jump to the last value in the array. Why is that ?

Code:
<script language="JavaScript" type="text/javascript">
<!--
window.onload= fade;
var i;
var ids = new Array("one", "two", "three");

function fade()
{
for (i=0 ; i<3; i++)
document.getElementsByTagName("div")[0].id=ids[i]
setTimeout("fade()", 500);
}
//-->
</script>
 
You are running all 3 timers at roughly the same time, so you'd pretty much only see the first and last iterations.

Try this:

Code:
<script type="text/javascript">
<!--

	window.onload = fade;
	var i = 0;
	var ids = new Array("one", "two", "three");

	function fade() {
		document.getElementsByTagName('div')[0].id = ids[i++];
		setTimeout('fade();', 500);
	}

//-->
</script>

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top