score:1

Whatever you are trying to do (which is not clear at all, mainly because there are many alternatives to properly creating an animation), the problem with your code is that you are appending a new SVG at every loop.

Instead of that, append the SVG just once and change its height:

var height1 = 0;
var svgContainer = d3.select("body").append("svg")
  .attr("width", 100);

for (let height1 = 0; height1 < 20; height1++) {
  setTimeout(function timer() {

    //make SVG container
    svgContainer.attr("height", height1);
    //Draw circle 
    var circle = svgContainer.append("circle")
      .attr("cx", 50)
      .attr("cy", 50)
      .attr("r", 50);
  }, height1 * 500)
}
<script src="https://d3js.org/d3.v4.min.js"></script>

On the other hand, if you really want to append a SVG at every loop and end up with a bunch of SVGs on top of each other (for whatever reason, it's not my place to judge), then you have to use position: absolute:

  var height1 = 0;

  for (let height1 = 0; height1 < 20; height1++) {
    setTimeout(function timer() {

      //make SVG container
      var svgContainer = d3.select("body").append("svg")
        .attr("width", 100)
        .attr("height", height1);
      //Draw circle 
      var circle = svgContainer.append("circle")
        .attr("cx", 50)
        .attr("cy", 50)
        .attr("r", 50);
    }, height1 * 500)
  }
svg {
  position: absolute;
}
<script src="https://d3js.org/d3.v4.min.js"></script>

score:1

To complement Gerardo Furtado’s response, pay attention to those two height1 variables in your script. I guess you didn’t intend to have two of them.

One is declared with var at the top scope of your script; the other one is declared with let and is local to your loop. I insist on the point that they are two different variables, and I suggest you remove the one you declared with var.


Related Query