Help - Search - Members - Calendar
Full Version: variable sends wrong
HTMLHelp Forums > Programming > Client-side Scripting
asmith
Hey guys

I have written this code : it suppose to move an image down :

CODE
<body onload="test()">
<script type="text/javascript">
function test()
{
var ii = 1;
while(ii < 100)
{
setTimeout(function(){move_it(ii);}, ii*100);
ii = ii + 10;
}
}
function move_it(x)
{document.getElementById('move').style.top = x+'px';alert(document.getElementById('move').style.top);}
</script>
<img id="move" style="position:absolute;top:1px" src="image.gif" />
</body>


I put the alert part to see how it changes each time, but it keep saying "101px" ;
I did the alert with the x : alert(x), and it showed "101" . why my x variable is 101 ?

Thanks
Christian J
QUOTE(asmith @ Nov 3 2008, 07:35 AM) *

I put the alert part to see how it changes each time, but it keep saying "101px" ;

The loop stops at 100 due to the

CODE
while(ii < 100)

asmith
It gives me like 10 alerts, and ALL of them are 101px.

At least I expect it to show increasing value in each alert.
Christian J
I think the loop creates a "queue" of delayed function calls, so when the timer begins calling move_it() the loop has already finished, and the last value is used.

Try putting an alert inside test() instead and you should see the increments.
asmith
How to do you make it so that "every second" the image move 10px down ?
Brian Chandler
CODE

var ii = 1;
while(ii < 100)


A good start is to abandon the programming style of variables called i, j, k, ii, and so on. What _is_ ii? What does it _mean_?

If, for example, you have a variable called $interval, meaning the interval in seconds between two javascript activations, you will not get confused about what it means.

(I think the answer you need, btw, is that the "move()" function needs to (a) do a move and (b) arrange for itself to get called again after $interval seconds.)


This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2010 Invision Power Services, Inc.