dimanche 22 mars 2015

javascript - break from a recursive call with setTimeout


I am doing a graphics animation with canvas where I draw the path of a particle : for this, I am calling a recursive function with a setTimeout call at the end of this function (this function is called drawPath() see below). That allows me to draw a segment of the path with a delay for each call.


My issue occurs when I try to break from this recursive call. Indeed, once I exit from this function, I would like to draw the last segment of the path and I would do it with a drawPathEnd() function.


Here's the script :



function main() {
button.onclick = function StartParticle() {
drawPath();
};
}

function drawPath() {

// Computing yt and t variable //
if ((i==0) && (delta[0]>0) && (delta[1]<0) && (delta[2]<0)) {
x_shift=x_final+pos_delta;
y_shift=a*x_shift+c;
if ((Math.pow(x_shift-xc[i],2)+Math.pow(y_shift-yc[i],2))<1)
delta_line=-step;
else
delta_line=step;

while ((yt<4) && (yt>-4) && (t<4) && (t>-4))
{t=t+delta_line;
yt=a*t+c;}

// Possible cases for drawing the last segment with drawPathEnd() //
if (intersection == false) {
if ((((yt>4) && (t<4)) || ((yt>0) && (t>4))) && (delta_line>0))
{direction='topright';
drawPathEnd();}
else if ((((yt>4) && (t>-4)) || ((yt>0) && (t<-4))) && (delta_line<0))
{direction='topleft';
drawPathEnd();}
else if ((((yt<-4) && (t<4)) || ((yt<0) && (t>4))) && (delta_line>0))
{direction='bottomright';
drawPathEnd();}
else if ((((yt<-4) && (t>-4)) || ((yt<0) && (t<-4))) && (delta_line<0))
{direction='bottomleft';
drawPathEnd();}
}
// Recursive call of drawPath function
setTimeout(function() {drawPath();}, 500);

}

function drawPathEnd() {

// Draw last segment
ctx.beginPath();
ctx.moveTo((x_final*scale)+width/2, (-y_final*scale)+height/2);
ctx.lineTo((t*scale)+width/2, (-yt*scale)+height/2);
ctx.closePath();
ctx.strokeStyle = 'blue';
ctx.stroke();
}


The problem is that the last segment of my animation is not drawn, what means that drawPathEnd() function doesn't seem to be called.


Initially, I did this animation with Matlab : I had a main loop where I put a sleep instruction for delay between two segments. In this version, I used break to exit from the loop and I called the drawPathend function to draw the last segment.


The code above never stops (I saw it with Web console) : it loops continuously.


Anyone could see how to stop it and draw this last segment ?


Thanks





Aucun commentaire:

Enregistrer un commentaire