0

I am adapting the following code, that redraws a line at the end of each transition.

function tick() {

// push a new data point onto the back
data.push(random());

// redraw the line, and slide it to the left
path
    .attr("d", line)
    .attr("transform", null)
  .transition()
    .duration(500)
    .ease("linear")
    .attr("transform", "translate(" + x(-1) + ",0)")
    .each("end", tick);

// pop the old data point off the front
data.shift();

}

Source of code: https://gist.github.com/mbostock/1642874

However, instead of automatically re-calling tick() at the end of every transition, I would like to check whether a certain boolean (myVar) is true, and only in that case re-call tick().

I have tried to write something like this, but the tick() function has stopped being re-called. Can someone please help me understand what's wrong. Thanks.

function tick() {

// push a new data point onto the back
data.push(random());

myVar = true //for now just hardcoding the value of myVar

// redraw the line, and slide it to the left
path
    .attr("d", line)
    .attr("transform", null)
  .transition()
    .duration(500)
    .ease("linear")
    .attr("transform", "translate(" + x(-1) + ",0)")
    .each("end", function() { if (myVar === true) return tick;});

// pop the old data point off the front
data.shift();

}

Note: The new code is adapted from JesperWe's answer here: Invoke a callback at the end of a transition

Community
  • 1
  • 1
codersun3
  • 165
  • 2
  • 4
  • 13

1 Answers1

1

In your example, the function you've replaced tick with is:

function() { if (myVar === true) return tick;}

However, D3 doesn't do anything with that return value. Instead you should write it as:

function() { if (myVar === true) tick();}

so when D3 calls that function, you can conditionally call tick yourself within the function you passed.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • The difference is that `tick` refers to the unevaluated function. D3 is calling it automatically when passed as the callback. In the modification, the function that is called returns the unevaluated `tick` function, which won't do anything -- you need to call it explicitly in this case as outlined in the answer. – Lars Kotthoff Jun 29 '15 at 21:32
  • Hmm...I've tried doing this suggestion and tick is not being recalled? The exact function now is: function tick() { data.push(random()); myVar = true path .attr("d", line) .attr("transform", null) .transition() .duration(500) .ease("linear") .attr("transform", "translate(" + x(-1) + ",0)") .each("end", function() { if (myVar === true) tick();}); data.shift(); } – codersun3 Jun 30 '15 at 15:29
  • Check what `myVar` is, then. Maybe the reason why is because it's unexpectedly `false` – Patrick Roberts Jun 30 '15 at 17:16