1

I'm writing a simulation demo, using d3. I'd like to show the evolution of the solution state.

If I embed the d3 rendering in the simulation loop, then the browser doesn't show anything until the end. It's busy, I suppose.

What I'd like to achieve is to do some calculating, some d3 updating, and then wait for all the transitions to complete, within the main loop.

Since the transitions are asynchronous, I can't figure out a way to wait for them.

It works to use setInterval to run the main loop, kinda, but not well.

Is there a "usual" way to do achieve the goal of lock-stepping a calculation with d3 transitions?

joel truher
  • 742
  • 7
  • 18

2 Answers2

2

Yes, like you stated, if your simulation is running synchronously (e.g. in one single for loop) then the browser never has a chance to render intermediate states.

Using setInteval is actually a reasonable solution, but you have to ensure that the interval is at least as long as the longest (d3-based) transition.

But it sounds like what you really want is to know exactly when the transition is finished, via a callback or event, and THEN call your simulation's step function to advance the state. In this case, have a read here: Invoke a callback at the end of a transition.

Although I've never tried that approach, I'm guessing that if you're transitioning multiple elements, then the transition's end event will get invoked multiple times –– once per each transitioning element. In this case you'll have to do some work to coalesce them into a single event. You'll might have to "count" the number of times the end event is invoked and only act on it when the count matches the expected number of elements. Alternatively, you might write conditional code to bind only to a single element's transition –– the element whose transition starts last or is expected to end last.

Hope this helps...

Community
  • 1
  • 1
meetamit
  • 24,727
  • 9
  • 57
  • 68
2

With HTML5 you also have a different way to approach this: have the simulation happen in a separate threaded Web Worker and have it pass the results back at each iteration to the main display thread.

http://www.html5rocks.com/en/tutorials/workers/basics/

In fact, yours is an almost perfect application for this.

Andrew Mao
  • 35,740
  • 23
  • 143
  • 224