Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell when a D3 force layout has stopped

I'm using D3's force layout to organize a network graph, and everything works smoothly.

However, I want to add a button to my UI so that the user can play/pause the layout process at will: I'd like to have a toggle button that reflects the current state of the layout: whether it's computing or not (d3 automatically will stop computing when the layout has stabilized). Is there a way to tell when force layout computing has finished and started? I expected some kind of event to handle this, but couldn't find one.

like image 697
protozoo Avatar asked Jul 16 '13 10:07

protozoo


2 Answers

Use the end event documented on the wiki.

d3.layout.force()
   .on('end', function() { console.log('ended!'); });

jsFiddle : http://jsfiddle.net/zschuessler/gRqv3/ | View console to see listeners in action.

like image 157
Zachary Schuessler Avatar answered Oct 22 '22 11:10

Zachary Schuessler


There isn't really a notion of having "stopped" computing the layout. Even when it looks like it's stationary, there may still be tiny changes. What you can do is check the value of alpha and interpret it as stopped if it falls below a threshold. In this case, you can set it to a negative value which will stop the layout explicitly. There is no specific event for this, but you can check your condition in the tick event handler.

like image 1
Lars Kotthoff Avatar answered Oct 22 '22 09:10

Lars Kotthoff