-
Notifications
You must be signed in to change notification settings - Fork 82
Timers
Andrew Burke edited this page Jun 2, 2016
·
2 revisions
Timers
We realized it would be important to give users of D3 timers the ability to turn these off once components unmount. Otherwise there would be memory leaks. If you follow the below steps timers will automatically be turned off when your React component unmounts. Since timers represent functionality they will have to placed inside the on mount event listener. Inside this function set a property on this called this.hasTimer and set it to true. If your timer is inside another function pass a reference down to the the 'this' object. In the timers callback function put a conditional that will return true if the hasTimer property has been switched to false. Here is an example below.
// Create .on('mount') function to wrap timers in.
svg.on("mount", function(){
// hasTimer property that will be binded to the React component
this.hasTimer = true;
//pass down a reference to this to the addTimer function
var that = this
addTimer(that);
});
// Fuction that will be called on mount with timer inside
function addTimer(that) {
var g = d3.select('svg').selectAll('g');
var width = 500,
height = 500,
n = 20;
d3.timer(function(t) {
g.attr("transform", function(d) {
return "translate(" + [width / 2, (d + 1) * height / (n + 1)] +
")scale(" + (Math.sin(d / 2 - t / 1000) + 1) / 2 + ",1)";
});
//return true if hasTimer has been set to false
if(that.hasTimer === false) return true;
});
}