Javascript 仅重复动画给定的次数

Javascript 仅重复动画给定的次数,javascript,d3.js,while-loop,Javascript,D3.js,While Loop,我试图通过D3.js重复一个动画,但只重复了x次。比如说10次。我使用了一个while循环,但它是一个很大的失败 <!DOCTYPE html> <meta charset="utf-8"> <body> <!-- load the d3.js library --> <script src="https://d3js.org/d3.v4.min.js"></script> <script> va

我试图通过D3.js重复一个动画,但只重复了x次。比如说10次。我使用了一个while循环,但它是一个很大的失败

<!DOCTYPE html>
<meta charset="utf-8">

<body>

<!-- load the d3.js library -->    
<script src="https://d3js.org/d3.v4.min.js"></script>

<script>

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

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', 250)     // position the circle at 250 on the y axis
        .transition()        // apply a transition
        .duration(2000)      // apply it over 2000 milliseconds
        .attr('cx', 920)     // 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(i) {
                while(i < 10) {
                    repeat;
                    i++;
                }
            });        
    };

};

circleTransition();

</script>
</body>

var svg=d3.选择(“主体”)
.append(“svg”)
.attr(“宽度”,960)
.attr(“高度”,500);
函数circlettransition(){
var timeCircle=svg.append(“circle”)
.attr(“填充”、“钢蓝”)
.attr(“r”,20);
重复();
变量i=0
函数重复(){
时间圈
.attr('cx',40)//将圆定位在x轴上的40处
.attr('cy',250)//将圆定位在y轴上250处
.transition()//应用转换
.duration(2000)//应用它超过2000毫秒
.attr('cx',920)//在x轴上将圆移动到920
.transition()//应用转换
.duration(2000)//应用它超过2000毫秒
.attr('cx',40)//在x轴上将圆返回到40
.关于(“结束”,功能(i){
而(i<10){
重复;
i++;
}
});        
};
};
圆圈转换();

我的循环“while”不起作用。谢谢您的帮助。

首先,因为您正在调用函数,所以它应该是
repeat()
,而不是
repeat
。另外,由于
i
是在函数
repeat
之外定义的,因此回调应该是:

.on("end", function() {
。。。不是:

.on("end", function(i) {
因为这里的
i
未定义的

但这不是真正的问题。这里最大的问题是暂停或延迟JavaScript循环很复杂:while循环将在几毫秒内立即运行到末尾,一次调用
repeat
十次

相反,您只需执行以下操作:

.on("end", function() {
    if (i > 9) return;
    i++;
    repeat();
});
或者,要保存一行,请执行以下操作:

.on("end", function() {
    if (++i > 9) return;
    repeat();
});
以下是演示:

var svg=d3.选择(“主体”)
.append(“svg”)
.attr(“宽度”,600)
.attr(“高度”,100);
函数circlettransition(){
var timeCircle=svg.append(“circle”)
.attr(“填充”、“钢蓝”)
.attr(“r”,20);
重复();
变量i=0
函数重复(){
时间圈
.attr('cx',40)//将圆定位在x轴上的40处
.attr('cy',50)//将圆定位在y轴上250处
.transition()//应用转换
.duration(2000)//应用它超过2000毫秒
.attr('cx',520)//在x轴上将圆移动到920
.transition()//应用转换
.duration(2000)//应用它超过2000毫秒
.attr('cx',40)//在x轴上将圆返回到40
.on(“结束”,函数(){
如果(++i>9)返回;
重复();
});
};
};
圆圈转换()