1

I want to implement an animation x-axis plotLines in highchart. When I click play button, there is a new plotline will be generated every one second to replace the last plotline in the x-axis.

Please see this fiddle. When I click click button, it is working properly. When I click play button. It only displays the first and last plotline.

var chart = Highcharts.chart('container', {

  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    plotLines: [{
      value: 0,
      color: 'blue',
      width: 2,
      zIndex: 10
    }]
  },

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


var drawNextPlotline = function(chart) {
  //console.log(i);
  //console.log(chart.xAxis[0].options);
  var newValue = (chart.xAxis[0].options.plotLines[0].value + 1) % 10;
  //var newValue = i;
  chart.xAxis[0].options.plotLines[0].value = newValue;
  chart.xAxis[0].update();
}

function sleep(miliseconds) {
  var currentTime = new Date().getTime();

  while (currentTime + miliseconds >= new Date().getTime()) {}
}

// the button action
var $playButton = $('#play');
var $clickButton = $('#click');

//
$playButton.click(function() {

  for (var i = 0; i <= 2; i++) {
    drawNextPlotline(chart);
    sleep(1000);
  }

});

$clickButton.click(function() {

    drawNextPlotline(chart);

});
Tester
  • 798
  • 2
  • 12
  • 32
  • Difficult to understand. what is the work of `$playButton.click` and `$clickButton.click`. What is your final requirement. – Deep 3015 Jan 11 '18 at 05:54

1 Answers1

1

If you insert your drawNextPlotline function inside a setInterval() you avoid to block the browser rendering like in for...loop:

var i = 0, nr = 5;
var intervalId = setInterval(function() {   
   if (i < nr) {
     drawNextPlotline(chart);
   } else {
     clearInterval(intervalId);
   }
   i++;
}, 1000)

Check the fiddle updated: https://jsfiddle.net/beaver71/18L1nng6/

beaver
  • 17,333
  • 2
  • 40
  • 66
  • Thanks! Can you explain what is `block the browser rendering liek in for...loop`? – Tester Jan 11 '18 at 15:52
  • This is related to Event Loop in JS (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop). You can find al lot of articles and samples to avoid "UI blocking" (e.g. https://stackoverflow.com/questions/27323772/javascript-function-and-ui-updates, https://stackoverflow.com/questions/24193548/how-to-do-a-loop-in-javascript-that-doesnt-block-the-ui) – beaver Jan 11 '18 at 16:22