protozoo
protozoo

Reputation: 570

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.

Upvotes: 9

Views: 3716

Answers (2)

Zachary Schuessler
Zachary Schuessler

Reputation: 3682

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.

Upvotes: 15

Lars Kotthoff
Lars Kotthoff

Reputation: 109282

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.

Upvotes: 1

Related Questions