setInterval() method

179 views
Skip to first unread message

Warren

unread,
Feb 28, 2017, 11:56:11 AM2/28/17
to Google Visualization API
Hi,

Please bear with me as I ask this question. Please know I am in the process of have a better understanding of Javascript, so this question may appear trivial to some. 

      //var chart = null;
        //var chartData = null;
        var chartOption = null;
        var divElements = ['chart_div_one', 'chart_div_two', 'chart_div_three'];
        var chartDataArray = new Array();
        var chartArray = new Array();
        google.charts.load('current', {'packages':['gauge']});
        google.charts.setOnLoadCallback(initializeCharts);

   
        function initializeCharts()
        {
            chartOption = {
                width: 320, height: 320,
                redFrom: 90, redTo: 100,
                yellowFrom:75, yellowTo: 90,
                minorTicks: 5
            };

            for(i = 0; i < divElements.length; i++)
            {
                var data = google.visualization.arrayToDataTable([
                    ['Label', 'Value'],
                    ['Speed', 0]
                ]);

                chartDataArray.push(data);
                    
                var c = new google.visualization.Gauge(document.getElementById(divElements[i]));
                chartArray.push(c);

                c.draw(data, chartOption);
            }

            for(i = 0; i < chartArray.length; i++)
            {
                setInterval(function() {
                    chartDataArray[i].setValue(0, 1, 40 + Math.round(60 * Math.random()));
                    chartArray[i].draw(chartDataArray[i], chartOption);
                }, 1000);
            
                //setJobInterval(chartArray[i], chartDataArray[i], chartOption, 1000);
            }
        }

        function setJobInterval(jobChart, jobData, jobOption, interval)
        {
            setInterval(function() {
                jobData.setValue(0, 1, 40 + Math.round(60 * Math.random()));
                jobChart.draw(jobData, jobOption);
            }, interval);
        }

Please direct your attention to the loop where setInterval() method is call, the purpose of the loop is to iterate through two arrays containing charts and chart data. In each iteration, setInterval() method is being call to update a Google Gauge chart every 1 second.  For some reason, having setInterval() directly within the loop doesn't work.  It is throwing an error "Uncaught TypeError: Cannot read property 'setValue' of undefined" on the console. 

However, when I moved the wrap the setInterval() method with another function call setJobInterval(). It works. 

So, my question is why it doesn't work in the loop ?

Reply all
Reply to author
Forward
0 new messages