geeky_monster
geeky_monster

Reputation: 8792

How Do I put a javascript time delay in a for loop?

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;


        }

Upvotes: 0

Views: 1602

Answers (4)

Lucas Green
Lucas Green

Reputation: 3959

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

Upvotes: 1

Amit
Amit

Reputation: 22076

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.

Upvotes: 1

web_bod
web_bod

Reputation: 5758

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);
   }
}

Upvotes: 1

Max
Max

Reputation: 5081

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);

Upvotes: 2

Related Questions