Alex
Alex

Reputation: 107

d3 transition wait for previous?

d3.select('#' + linkId[0]).transition().duration(2500).attr('stroke', 'green');
d3.select('#' + nodeId[0]).transition().duration(5000).attr('fill', 'blue');

I have the above code that is animating a graph traversal. I want the second transition to only activate (and preferably remove the duration) once the link has been transitioned. How would i accomplish this? I have tried putting the whole second line of code within a timeout like so:

setTimeout(() => {  d3 transition here }, 2500);

However this completely messed up the timing of events. Im basically looking for something similar to python where you can call .sleep(milliseconds) to specify code execution wait a certain amount of time.

Upvotes: 2

Views: 1467

Answers (1)

Andrew Reid
Andrew Reid

Reputation: 38151

There are two quick options available:

transition.delay()

You could use transition.delay(time) which allows you to specify a delay before a transition starts. This would look like:

d3.select('#' + linkId[0]).transition().duration(2500).attr('stroke', 'green');
d3.select('#' + nodeId[0]).transition().delay(2500).duration(5000).attr('fill', 'blue');

While simple, I'd suggest using the next approach instead.

transition.on("end", ... )

Another option is to use transition.on("end", function() { /* set up next transition */ }). Now .on("end",callbackFunction) will trigger on the end of each transition (if transitioning many elements, it'll trigger when each element finishes its transition), but you are transitioning single elements (as IDs are unique), so you could use something like this:

d3.select('#' + linkId[0]).transition()
  .duration(2500)
  .attr('stroke', 'green')
  .on("end", function() {
      d3.select('#' + nodeId[0]).transition().duration(5000).attr('fill', 'blue');
  })

If you had many elements transitioning simultaneously you'd need to modify this slightly to check to see if any transitions were still in progress before starting the next transition.

Upvotes: 3

Related Questions