Reputation: 8792
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
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
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
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