Ok, this one is for the hardcore "best practices" scripters who can increase the wider communities learning curve.
The basic problem is that a setTimeout() or setInterval() inside a while loop does not work. The delay is not respected. I have read on many other forums that javascript while loops ignore setTimeout().
The code below is supposed to move an image up the screen by increments of 3 pixels on a delay of 500 milliseconds per iteration. My setTimeout() calls a dummy function like i=i; to best emulate a delay function.
I would rather not wrap this whole loop inside a function. Then I would have to pass many parameters, which is not cool. Does anyone have a solid solution??Code:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> /*<![CDATA[*/ fieldSector = new Array() // fieldSector[0] = "0,0,60,66"; fieldSector[1] = "60,0,120,66"; fieldSector[2] = "120,0,180,66"; fieldSector[3] = "180,0,240,66"; function trackObj() { var playerID = 'player1'; // array 1 value if (sector <= 2) { var direction = "south"; } else { var direction ="north"; } var distance = 200; var action="go"; while (action=="go") { var em = document.getElementById(playerID); var running = parseInt(em.style.top); // gets the xposition location of player as a number if (direction=="north") { if (distance>=0) { running+=-3; // travel X pixels distance distance=distance-3; // remove x pixels from distance em.style.top=running+"px"; // runs extra distance setInterval("argumentHere()", 500); // small motion delay } else { action="stop"; //end while loop return } } } } /*]]>*/ </script> <title>timeout and while loop </title> </head> <body> <img id="player1" src="somewhere.gif" /> </body> </html>



Reply With Quote


Bookmarks