0

I am working on an animation using Javascript and HTML5 CAnvas. How do achieve a delay ( non-blocking ) within a for loop ? I want to make sure that the second line doesnt get drawn before the delay is over .

for (i=1;i<coor.length;i++)

        {
            context.beginPath();
            var end_point=coor[i];
            var x1y1=start_point.split(',');
            var x2y2= end_point.split(',');


            context.moveTo(parseInt(x1y1[0]),parseInt(x1y1[1]));
            context.lineTo(parseInt(x2y2[0]),parseInt(x2y2[1]));
            context.stroke();

            start_point=end_point;


        }
1
  • Added actual code . HTML5 canvas Commented May 16, 2012 at 23:36

4 Answers 4

2

If you're using jQuery, check out the .delay() API.

el.delay(800).fadeIn(400);

inside the for-loop, assuming el is a jQuery object outside the for loop.

Otherwise, I'd just use setTimeout(function(){ ... }, i * 100);

Sign up to request clarification or add additional context in comments.

1 Comment

@Peter yeah, okay so .delay() actually wouldn't do what one wants -- I was hoping/assuming that there would be an arbitrary callback that one could chain, but it actually looks like there isn't. I'll leave the jQuery bit in so your comment makes sense :P
1

It would be better if you could re-factor your code:

function animate(position)
{
   // do stuff based on position

   if(position++ < 100){
       setTimeout(function(){animate(position);}, 100);
   }
}

1 Comment

I did this . Works like magic .. Perfect . Thanks for the timely help :)
1

This code will create delay of 2 seconds.

var i=0;    
setInterval(function () {
    context.beginPath();
                var end_point=coor[i];
                var x1y1=start_point.split(',');
                var x2y2= end_point.split(',');


                context.moveTo(parseInt(x1y1[0]),parseInt(x1y1[1]));
                context.lineTo(parseInt(x2y2[0]),parseInt(x2y2[1]));
                context.stroke();
                i++;
                start_point=end_point;

    }, 2000);

Through this code you can omit FOR loop.

Comments

1

If you are looking for a blocking sleep call, JavaScript doesn't have native support for that.

if however you are simply looking to execute a piece of code at a fixed interval, you can use

The <callback> can be any function, anonymous or named.

If you're planning to use it for animation, you ought to look into requestAnimationFrame as a superior alternative

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.