【发布时间】:2015-06-30 11:15:44
【问题描述】:
我尝试创建一个活的折线图。我总是显示固定数量的点,添加一个新点意味着删除一个旧点。为此,我使用间隔计时器重绘图表。
在我运行分析器并查看内存消耗之前,这非常有效。这个图表每一步都消耗大量内存,而且越来越多。我看不出一个明显的原因,因为在新值是 push() 之后数据是 shift() 在数组之外。
var data = [{
"key" : "Long",
"values" : getData()
}];
var chart;
function redraw() {
nv.addGraph(function() {
var chart = nv.models.lineChart().margin({
left : 100
})
//Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
//.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true);
//Show the x-axis
chart.xAxis.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
chart.yAxis.tickFormat(d3.format(',.1%'));
d3.select('#chart svg').datum(data)
//.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
}
function getData() {
var arr = [];
var theDate = new Date(2012, 01, 01, 0, 0, 0, 0);
for (var x = 0; x < 30; x++) {
arr.push({
x : new Date(theDate.getTime()),
y : Math.random() * 100
});
theDate.setDate(theDate.getDate() + 1);
}
return arr;
}
setInterval(function() {
var long = data[0].values;
var next = new Date(long[long.length - 1].x);
next.setDate(next.getDate() + 1)
long.shift();
long.push({
x : next.getTime(),
y : Math.random() * 100
});
redraw();
}, 1500);
怎么了?
【问题讨论】:
-
内存泄漏可能是因为您每隔 1500 秒重新绘制整个图表。看看他的answer。它将向您展示如何仅更新
chart data。