score:1

first, since you're calling the function it should be repeat(), not repeat. also, since i is defined outside the function repeat, the callback should be just:

.on("end", function() {

... not:

.on("end", function(i) {

because here i is undefined.

but that's not the real problem. the biggest problem here is that it's complicated pausing or delaying javascript loops: that while loop will run immediately to the end, in few milliseconds, calling repeat ten times at once.

instead of that, you can just do:

.on("end", function() {
    if (i > 9) return;
    i++;
    repeat();
});

or, to save 1 line:

.on("end", function() {
    if (++i > 9) return;
    repeat();
});

here is the demo:

var svg = d3.select("body")
  .append("svg")
  .attr("width", 600)
  .attr("height", 100);

function circletransition() {
  var timecircle = svg.append("circle")
    .attr("fill", "steelblue")
    .attr("r", 20);
  repeat();

  var i = 0

  function repeat() {
    timecircle
      .attr('cx', 40) // position the circle at 40 on the x axis
      .attr('cy', 50) // position the circle at 250 on the y axis
      .transition() // apply a transition
      .duration(2000) // apply it over 2000 milliseconds
      .attr('cx', 520) // move the circle to 920 on the x axis
      .transition() // apply a transition
      .duration(2000) // apply it over 2000 milliseconds
      .attr('cx', 40) // return the circle to 40 on the x axis
      .on("end", function() {
        if (++i > 9) return;
        repeat();
      });
  };

};

circletransition();
<script src="https://d3js.org/d3.v4.min.js"></script>


Related Query