Question

I'm attempting to animate my google line chart multiple times, but my chart refuses to transition more than once. In the example below it will display the first data set and transition right to the fourth, skipping the two in the middle. How can I fix this behavior?

    <script type="text/javascript">
      var options;
      var chart;
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(prep);
      function prep(){
        chart = new google.visualization.LineChart(document.getElementById('chart'));
        options = {
            colors: ['Red','Purple','Blue'],
            animation:{duration: 1000,easing: 'linear'}
        };
        drawChart();
      }
      function triggerChart(data){
        chart.draw(data, options);
      }
      function drawChart(){

        data = google.visualization.arrayToDataTable([
          ['Hour', 'First', 'Second', 'Third'],
          [1,1,2,3],
          [2,2,3,4]
        ]);
        triggerChart(data);

        data = google.visualization.arrayToDataTable([
          ['Hour', 'First', 'Second', 'Third'],
          [3,2,3,4],
          [4,5,6,7]
        ]);
        setTimeout(function(){triggerChart(data);},2000);

        data = google.visualization.arrayToDataTable([
          ['Hour', 'First', 'Second', 'Third'],
          [5,5,6,7],
          [6,7,8,9]
        ]);
        setTimeout(function(){triggerChart(data);},4000);

        data = google.visualization.arrayToDataTable([
          ['Hour', 'First', 'Second', 'Third'],
          [7,11,12,13],
          [8,12,13,14]
        ]);
        setTimeout(function(){triggerChart(data);},6000);
      }
    </script>
    <div id="chart" style="width:900px;height:600px"></div>
Was it helpful?

Solution

Function triggerChart() is called always with same set of data and it is the last one.

You have to move assignment of data to setTimeout call.

Update: Reason for this behavior: data is global variable and sequence of execution is:

  • first data assignment
  • call of triggerChart(data)
  • second data assignment
  • third data assignment
  • fourth data assignment
  • call of triggerChart(data)
  • call of triggerChart(data)
  • call of triggerChart(data)

Another solution is to left data out of setTimeout() but in that case you have to use 4 different variable names for data. For example data1, data2, data3, and data4.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top