How to animate drawing a sequence of segments

I would like to draw a point, and after 1 second I would like to make the next point. Is this possible?

I already tried:

function simulate(i) { setTimeout(function() { drawPoint(vis,i,i); }, 1000); } for (var i = 1; i <= 200; ++i) simulate(i); function drawPoint(vis,x,y){ var svg = vis.append("circle") .attr("cx", function(d) { console.log(x); return 700/2+x; }) .attr("cy", function(d) { return 700/2+y; }) .attr("r", function(d) { console.log(x); return 6; }); } 

Unfortunately this does not work. It just draws the whole line at once.

+5
source share
1 answer

This will not work, because the for loop will immediately start until the end, setTimeouts will be scheduled at the same time, and all functions will fire at the same time.

Instead, do the following:

 var i = 1; (function loop(){ if(i++ > 200) return; setTimeout(function(){ drawPoint(vis,i,i); loop() }, 1000) })(); 

Explanation:

This IIFE will be launched for the first time with i = 1 . Then if increments i ( i++ execution) and checks if it is greater than 200. If so, the loop function is returned. If it is not, a setTimeout planned, which again calls drawnPoint and the loop function itself.

+5
source

Source: https://habr.com/ru/post/1260259/


All Articles