Ales Ales - 1 year ago 106
Javascript Question

How to draw Dygraphs immediately after each pass in a for loop?

I am using Dygraphs for displaying multiple (10) graphs in a page. The Dygraph object is created in a for loop. All those graphs are visible/drawn at once after the loop is finished. It takes about 400ms to create my Dygraph object with about 50000 values, so it is about 4s without response on the page (for 10 graphs). Is there any way to draw each graph immediately after every single loop pass?

function drawGraph(chartData, chartOptions) {
var graph = new Array();
var index = 0;
for (var chart in chartData) {
graph[index] = new Dygraph(document.getElementById(chart + "_graph"), chartData[chart], chartOptions[chart]);

Answer Source

You could define some vars outside of the function on the global scope, then save the data to those vars, then use a timer to one by one iterate through the saved data and draw each graph one at a time with a delay in between them...

/* define the parts of your function outside of the scope of the drawGraph() function */
var idx = 0;
var _chartData = [];
var _chartOptions = [];
var _charts = [];
var graph = [];

function drawGraph(chartData, chartOptions) {
  graph = []; // initialize
  idx = 0;

  /* store the relevant data into memory */
  for (var chart in chartData) {
    _chartData[chart] = chartData[chart];
    _chartOptions[chart] = chartOptions[chart];

  /* start the process of drawing each graph one by one */

function draw_next() {

  // grab our data saved in memory
  var tmp_chart = _charts[idx];

  /* this tells us when no more charts exist (sorta) */
  if (tmp_chcart != undefined) {
    graph[idx] = new Dygraph(document.getElementById(tmp_chart + "_graph"), _chartData[tmp_chart], _chartOptions[tmp_chart]);

    /* in 1 ms run this function again */
    setTimeout(function() {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download