1

I have a chart and a button which calls a very heavy processing, as in this example: http://jsfiddle.net/v97e5vs1/1/

$button.click(function () {
        chart.showLoading();
        for (var i=0;i<20;i++) {
                var d=[];
            for (var j=0;j<12;j++) {
                d.push(Math.random()*200)            
                        }
        chart.addSeries({data:d});    
        }
        chart.hideLoading();
});

However, the showLoading function doesn't work as expected: the broser window hang up until the processing is finished.

What's wrong?

tic
  • 4,009
  • 15
  • 45
  • 86
  • 1
    showLoading() just changes the display of the chart - it does not do anything more - if your loop freezes the browser then you need to move the loop to a webworker process or use some async technique like the one in the answer from here https://stackoverflow.com/questions/714942/how-to-stop-intense-javascript-loop-from-freezing-the-browser – morganfree Jul 21 '17 at 10:46

1 Answers1

2

To improve performance you can ask highcharts not to redraw when you add the series by setting the redraw parameter to false. Once adding is complete redraw can be called.

Not the prettiest solution but you can draw the chart within a setTimeout to allow it enough time to display the loading message.

Example:

// the button handler
var isLoading = false,
  $button = $('#button'),
  chart;

chart = Highcharts.chart('container', {

  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  },

  series: [{
    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
  }]
});



$button.click(function() {
  chart.showLoading();

  setTimeout(function() {
    for (var i = 0; i < 20; i++) {
      var d = [];
      for (var j = 0; j < 12; j++) {
        d.push(Math.random() * 250)
      }
      chart.addSeries({
        data: d
      }, false);
    }

    chart.redraw();
    chart.hideLoading();
  }, 100);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div>
<button id="button">Show loading</button>
H77
  • 5,859
  • 2
  • 26
  • 39
  • The "heavy processing" function of my code was only an example. I don't use `addSeries` function. Anyway, I thank you for your reply citing also `setTimeout` that I was thinking about, too. – tic Jul 21 '17 at 10:08
  • 1
    Depending on what the _heavy processing_ involves you could make use of the [Worker API](https://developer.mozilla.org/en/docs/Web/API/Worker) – H77 Jul 21 '17 at 10:14