如何在for循环中每次传递后立即绘制Dygraphs?

时间:2016-11-19 13:21:14

标签: javascript for-loop dygraphs

我使用Dygraphs在页面中显示多个(10)图形。 Dygraph对象在for循环中创建。循环结束后,所有这些图形都可以立即显示/绘制。创建具有大约50000个值的Dygraph对象大约需要400ms,因此在页面上没有响应的情况下大约为4s(对于10个图形)。有没有办法在每次循环后立即绘制每个图形?

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]);
    index++;
  }
}

1 个答案:

答案 0 :(得分:0)

您可以在全局范围内定义函数外部的一些变量,然后将数据保存到这些变量,然后使用计时器逐个迭代保存的数据并一次一个地绘制每个图形并延迟他们之间......

/* 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];
    _charts.push(chart);
  }

  /* start the process of drawing each graph one by one */
  draw_next();
}

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]);
    idx++;

    /* in 1 ms run this function again */
    setTimeout(function() {
      draw_next();
    },1);
  }
}