【问题标题】:nvd3 living chart Memory Leak [duplicate]nvd3 live chart Memory Leak [重复]
【发布时间】: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

标签: ajax nvd3.js


【解决方案1】:

感谢@shabeer90 提示,我找到了解决方案。我只需要在图表构建完成后调用以下方法。

function update() {
    var data = getData();

    // Update the SVG with the new data and call chart
    chartData.datum(data).transition().duration(500).call(chart);
    nv.utils.windowResize(chart.update);
};

就是这样!

【讨论】:

  • 很高兴它有帮助。我将标记这个重复项,这样我们就不会重复相同的答案。请接受它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 2011-09-20
  • 2022-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
相关资源
最近更新 更多