How to use timer in d3 V3?

Viewed 1760

I have a function triggerWave() which makes the points on the canvas animate in the wave form. I am using d3.ease('quad-in') for easing and I would like to use d3.timer() to make the triggerWave() function call over 200ms timeframe. I am out of luck in finding the tutorials or examples on d3.timer.

triggerWave() {
  //function logic
  let count = 0;
  let xScale = d3.scale.linear().range([1,2]); // want the value to change from 1 to 2.
  let zScale = d3.scale.linear().domain([0, 200]); // 200 ms.
  let value = xScale(d3.ease('quad-in')(zScale(count)));
  if(count < 200){
   count++;
   d3.timer(() => triggerWave());
  } else {
    // do something
  }
  this.wave.next({currentFrame: value});
}

When I call d3.timer() as above, the triggerWave() function gets called infinite times and never stops. I want to manipulate or control the time. In my case, I want the timer() to be triggered for 200ms.

How can I understand how to use the d3.timer() function?

3 Answers

I use d3.js v3, and the timer can be stopped by any user action. In the d3.js docs it is shown to use it as:

d3.timer(function(elapsed) {
  console.log(elapsed);
  return elapsed >= 1000;
});

I have few examples in which the animation is forever and there is no reason to set a limit on it. Checking the standalone d3.timer which comes with a stop(), I found that it behaves quite slow comparing it with the default timer included in the v3 toolset, probably for some version incompatibility.

The solution is use is to:

var timer_1_stop=false;

set it as global var accesible from the page scope. Then the timer:

const run=function(){
  //...
  d3.timer(function() {
    voronoi = d3.geom.voronoi(points).map(function(cell) { return bounds.clip(cell); });
    path.attr("d", function(point, i) { return line(resample(voronoi[i])); });

    return timer_1_stop;
  });
}

const stopVoro=function(){
  timer_1_stop=true;
}

It allows to do:

class Menu extends React.Component {
  render(){
    return(<ul>
      <li><span onClick={()=>{stopVoro()}}>StopVoro</span></li>
    </ul>)
  }
}
Related