Derick Kolln Derick Kolln - 3 years ago 100
Javascript Question

How to delay a loop? Or how to make a loop slower?

I just asked a similiar question before, but now I decided to change it a little bit into a new question. I use d3.js.
The Array called A stores 3 colours and I want to go through a loop that fills my element link. Unfortunally this loop is so fast, only the very last element gets visible on screen, that means only the color green.
How can I delay this process? That means turn the links blue, wait 2 seconds, turn them red, wait another 2 seconds and at last turn them green?

var A = ["blue", "red", "green"]

for ( var i = 0; i < A.length; i++){


link.style("stroke", function(d)
{

return A[i];



}
)
};

Answer Source

There are quite a few plain javascript answers, since you are using d3, I'll offer a way to use d3 to achieve this effect (with which I've included a transition):

var svg = d3.select("body")
  .append("svg")
  .attr("width",400)
  .attr("height",400);
  
var circle = svg.append("circle")
  .attr("cx",100)
  .attr("cy",100)
  .attr("r",20)
  .attr("stroke","black");
  
var colors = ["orange","steelblue","lawngreen","pink","darkgreen","purple"];


var i = 0
transition(i);

function transition(i) {
  if (colors[i]) {
  circle.transition()
    .attr("fill",function() { return colors[i]; })
    .duration(1000)
    .each("end", function() { transition(++i) });
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

The .each method (v3) is now .on (v4), and is invoked on each transition end (for each element), so if transitioning multiple elements, you would need to check to see how many elements have finished transitioning:

var svg = d3.select("body")
  .append("svg")
  .attr("width",400)
  .attr("height",400);
  
var circles = svg.selectAll("circle")
  .data([1,2])
  .enter()
  .append("circle")
  .attr("cx",function(d) { return d * 100; })
  .attr("cy",100)
  .attr("r",20)
  .attr("stroke","black");
  
var colors = ["orange","steelblue","lawngreen","pink","darkgreen","purple"];


var i = 0
transition(i);

function transition(i) {
  var n = 0; // # of elements done this transition
  if (colors[i]) {
  circles.transition()
    .attr("fill",function() { return colors[i]; })
    .duration(1000)
    .each("end", function() { if (++n == circles.size()) { transition(++i) } });
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download