You should add a sleep primitive in your drawing code. However in javascript, rather than with sleep or wait primitives, this is accomplished in an event-directed manner with setInterval
or setTimeout
. As demonstrated:
var sec = 1000; // milliseconds
var totalDrawingTime = 5*sec;
var numPointsToDraw = [calculate this];
var waitTimePerPoint = totalDrawingTime/numPointsToDraw;
function slowlyDrawCurve(...) {
var x = ...;
function drawNextPointAndWait() {
x += ...;
if (x < MAX_CANVAS_SIZE) {
y = f(x);
point = [x,y];
dispatch_to_canvas_function(point);
setTimeout(helper, waitTimePerPoint);
}
}
drawNextPointAndWait();
}
edit
Demonstration here: http://jsfiddle.net/eJVnU/4/
This was actually a little more interesting. Namely, if you are drawing at intervals on order of a few milliseconds (1000 points means 1 millisecond per update!), you need to be careful how you deal with javascript's timers. The javascript events scheduled with setTimeout
may not trigger for a few milliseconds or more, making them unreliable! Therefore what I did was figure out when each segment should be completed by. If we were running ahead of schedule by more than a few milliseconds, we did a setTimeout
, BUT, if we were otherwise running behind schedule, we directly performed a recursive call to the segment-drawing routine, shortcutting the event-handling system. This also ensures that the drawing is done smoothly to the human eye, as long as the segments are of roughly equal length.
(If you wanted it done even more smoothly, you could calculate the length of the segment drawn, keep the sum total of arclength drawn, and divide that by some fixed constant rate arclength_per_second
to figure out how long things should have taken.)