本文介绍了For循环在D3.js中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java和D3.js的新手,正在尝试在for循环中连续更改一个circle元素.本来是要每秒改变圆的半径,但事实证明半径只是跳到50,而忽略了26到49.

I'm new to Javascript and D3.js and trying to change a circle element continuously in a for loop.It's meant to change the radius of the circle every second but it turns out that the radius just jumps to 50, ignoring 26 to 49.

这是我的代码.

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

</style>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
    var width = 960,
            height = 1160;
    var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height);

    svg.append("circle").attr("cx", 100).attr("cy", 100).attr("r", 25).style("fill", "purple").attr('id','cc');

    for(i=26;i<=50;i++){
        var now=d3.select('#cc');
        now.transition().duration(1000).attr("r",i);
    }
</script>

推荐答案

在JavaScript中,当您说:

In JavaScript, when you say:

for(i=26;i<=50;i++){
    var now=d3.select('#cc');
    now.transition().duration(1000).attr("r",i);
}

不要以为for循环会先等待 i = 26 转换完成,然后再移至 i = 27 .实际上,它为 i = 26 调用了 now.transition().duration(1000).attr("r",i); 语句,然后IMMEDIATELY移至循环的下一次迭代.由于循环的 i = 26 i = 50 之间的时间差是无限的(速度仅受处理器速度的限制,今天是GHz)),您可以认为所有过渡都一起调用,并且立即立即观察到最后一个过渡的效果.

Don't think that the for loop will wait for the i=26 transition to finish before it moves on to i=27. In fact, it invokes the statement now.transition().duration(1000).attr("r",i); for i=26 and then IMMEDIATELY moves onto the next iteration of the loop. Since the time difference between the i=26 and i=50 iteration of the loop is infinitesimal (the speed limited only by the speed of the processor, which is in GHz today), you can think that ALL transitions are invoked together, and the effect of the last one is observed, immediately.

执行此操作的一种方法是在每次调用之前设置时间延迟,并记住,该时间延迟必须是绝对的,因为所有迭代几乎都在同一时刻被调用.例如,

One way to do this is to set a time delay before each call, and remember, that time delay has to be ABSOLUTE, since all the iterations are called almost at the same instant of time. For example,

0秒后调用的第一条语句.
1秒后调用第二条语句.
第三个语句在2秒后调用.

The first statement called after 0 seconds.
The second statement called after 1 seconds.
The third statement called after 2 seconds.

只有这样,您才能看到两次通话之间的相对差为1秒.

Only then will you see a relative difference of 1 second between the calls.

另一种方法是使用 setTimeout()例程递归地执行此操作.推荐这种方法.

ANOTHER approach is to do it recursively using the setTimeout() routine. This approach is recommended.

var i = 26;

function myLoop () {
    setTimeout(function () {
        var now=d3.select('#cc');
        now.transition().duration(1000).attr("r",i);
        i++;
        if (i < 50) {
            myLoop();
        }
    }, 1000) // change this time (in milliseconds) to whatever you desire
}

myLoop(); // first call

这篇关于For循环在D3.js中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 00:35