Joe Almore Joe Almore - 1 month ago 14
Javascript Question

Google Chart flickering on consecutive data load

I have this piece of

JavaScript
code to load a Google chart:

<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
setInterval(drawChart, 1000);

function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;

// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

var options = {
chart: {
title: 'Box Office Earnings in First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)'
},
width: 900,
height: 500
};

var chart = new google.charts.Line(document.getElementById('chart'));

chart.draw(data, options);
}
</script>


This code loads the data from a Restful endpoint to draw the chart. The thing is that as this is a chart to monitor remote variables it has to continuously refresh itself to fetch and show the most recent data. It works well and the data is fetched and shown correctly, but the chart flickers endlessly, so what can I do to avoid the chart to flick on every data load?

Thanks in advance.

Answer

to prevent "flickering", save a reference to the chart,

and draw the same chart with new data

instead of creating a new chart every time

also, be sure to wait on the 'callback' before drawing charts

and highly recommend not using async: false on the $.ajax call

recommend setup as follows...

google.charts.load('current', {
  callback: function () {
    var chart = null;

    var options = {
      chart: {
        title: 'Box Office Earnings in First Two Weeks of Opening',
        subtitle: 'in millions of dollars (USD)'
      },
      width: 900,
      height: 500
    };

    drawChart();
    setInterval(drawChart, 1000);

    function drawChart() {
      $.ajax({
        url: "getData.php",
        dataType:"json",
      }).done(function (jsonData) {

        var data = new google.visualization.DataTable(jsonData);

        if (chart==null)
           chart = new google.charts.Line(document.getElementById('chart'));

        chart.draw(data, options);

      }).fail(function (jq, text) {
        console.log(text);
      });
    }
  },
  packages: ['line']
});

note: also recommend not using a Material chart, several options don't work

otherwise, this would be an ideal scenario to introduce animation