I’ve been trying to modify a Google charts example in order to have three pie charts sitting next to eachother, and though i can get it to work satisfcatorily, I find that i need to decrement a counter which logically I feel should be left alone. I’d be grateful if anyone would cast an eye over this working code snippet and and explain why the manual decrementing of a loop counter (see the comment) is necessary, because without it the code fails (it only shows one chart).
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
var num_charts = 3;
var userdata = new Array(num_charts);
var fn_array = new Array(num_charts);
for ( var i=0; i<num_charts; i++ )
{
userdata[i] = new Array(
['Work', 1 + Math.floor(Math.random()*10)],
['Eat', 1 + Math.floor(Math.random()*10)],
['Commute', 1 + Math.floor(Math.random()*10)],
['Watch TV', 1 + Math.floor(Math.random()*10)],
['Sleep', 1 + i ]
);
fn_array[i] = function() {
// Need to decrement i for it to work, but why??? The value
// of i inside this function is one greater than the corresponding
// fn_array index, but I don't see why.
i--;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows(userdata[i]);
var options = {
width: 400, height: 300,
title: 'Hello ' + i
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'+i));
chart.draw(data, options);
}
}
for ( var j=0; j<num_charts; j++ )
google.setOnLoadCallback(fn_array[j]);
</script>
</head>
<body>
<span id="chart_div0"></span>
<span id="chart_div1"></span>
<span id="chart_div2"></span>
</body>
</html>
Since you use the same variable inside the callback, every call of the callbacks will have the same value, decreasing its value inside the callback cause its value be different every time. Since javascript is single threaded(not counting webworkers) this is ‘fine’. If you fell awkward with it simple do: