Updating Nvd3 chart priodically

by Shabeer Sheffa

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.css">
<div id="chart">
    <svg></svg>
</div>

JavaScript

var data = [{
    "key" : "Long",
    "values" : getData()
}];
var chart;

// Maintain an Instance of the SVG selection with its data
var chartData;

//function redraw() {

    nv.addGraph(function() {
        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%'));

        chartData = d3.select('#chart svg').datum(data);
        chartData.transition().duration(500).call(chart);

        nv.utils.windowResize(chart.update);
        return chart;
    });
//}

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

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
    });
    updateChart();
}, 1500);