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

More Query from same tag