Paul LeBlanc <pa***********@msn.com> writes:
Hi Lasse,
Sorry no code but I thought I was asking about code that I have yet to
write! Here's a sample of what I have written. Again, this code works
when I generate the (x,y) coordinates with a mousedown or mousemove, and
all the timeouts DO WORK. The problem is that when I feed the
coordinates programatically with a loop then I only get the initial
positions and final positions drawn to display.
Here's how I generate the coordinates and call the moveDucks function:
function posGenerator(xaxis, yaxis) {
x=xaxis;
y=yaxis;
x2 = x
y2 = y
var dummy2;
do {
x2+=1;
y2-=1;
setTimeout('dummy2 = moveDucks x2,y2)',500);
I assume there is a parenthesis missing here:
setTimeout('dummy2 = moveDucks(x2,y2)',500);
Notice that you embed the variable *names* x2 and y2 in the string.
That means that when the code is executed (in 500 milliseconds), the
value of x2 and y2 at that point is used.
I think you have slightly misunderstood how setTimeout and
clearTimeout works (and trust me, you are not the first to do that).
setTimeout schedules some code to be executed after some time.
The call to setTimeout itself return immediately.
clearTimeout;
clearTimeout is a function that can prevent a scheduled timeout.
Here, you don't call the function, so the line does nothing.
The argument to clearTimeout is a timeout identifier returned by
setTimeout.
TextBox4.value=(x2+","+y2)
} while (x2<500);
Since setTimeout returns immediately, you might run through this entire
loop before 500 milliseconds have passed. At that time, x2 and y2
have their final values. Then 500 scheduled calls to moveDucks happens,
all setting the same position.
What you can do to fix this:
1) Embed values in the scheduled code instead of variable names:
setTimeout('moveDucks(' + x2 + ',' + y2 + ')',500);
You might want to schedule later events at a later time, e.g.,
make a counter and multiply the 500 by the counter. Then the steps
will happen with half second intervals.
2) Put the position updating in the scheduled code.
setTimeout('x2+=1;y2-=1;moveDucks(x2,y2)',500);
Again, you don't want all the events to happen at the same time.
3) A completely different approach:
Use setInterval instead of setTimeout. It will automatically call
every <delay> milliseconds, until you stop it.
Use a local function as argument to setInterval, so you have the
xaxis and yaxis variables in scope. It saves you from making too
many global variables.
Update the values in the scheduled code.
---
function posGenerator(xaxis, yaxis) {
var intervalId = setInterval( function () {
xaxis+=1;
yaxis-=1;
moveDucks(xaxis,yaxis);
if (xaxis >= 500) {
clearInterval(intervalId);
}
}, 500);
}
---
Hope this helps.
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'