1

I am trying to create a line chart with Chart.js, that updates every second using AJAX. I am quite new to JavaScript.

I had some problems doing it, my main issue at the beginning being how to initialize myNewChart.Line(data, options); with 20 samples from my database, and then use myNewChart.addData(data.datasets[0].data, data.labels);, just adding one sample every second to the chart. I had both calls on the success function of the AJAX call.

Now I have it working, but I am sure there is a better way to do it because it is quite slow, and I can see that the CPU usage goes up, and even more if I try to change the size of the window.

Here is the code:

function get_data() {
    if (data === undefined){
        $.ajax({
            type: 'GET',
            url: '/stream/20',
            dataType: 'json',
            success: function (response) {
                console.log(response);
                time = response.labels.map(function (x) {return moment(x).format('HH:mm:ss');});
                data = {
                    labels : time.reverse(),
                    datasets : [{data : response.DataSets.reverse()}]
                };
                window.myNewChart = myNewChart.Line(data, options);
            }
        });               
   }else{
        $.ajax({
            type: 'GET',
            url: '/stream/1',
            dataType: 'json',
            success: function (response) {
                console.log(response);
                time = response.labels.map(function (x) {return moment(x).format('HH:mm:ss');});
                data = {
                    labels : time,
                    datasets : [{data : response.DataSets}]
                };
                console.log(data.datasets[0].data, data.labels);
                myNewChart.addData(data.datasets[0].data, data.labels);
                myNewChart.removeData();
            }
        });  
    }
}

var data;

var ctx = $('#chart').get(0).getContext("2d");

var myNewChart = new Chart(ctx);

var options = { animation: false,
                responsive: true,
                pointDot : false,
                datasetFill : false,
                scaleShowGridLines : false,
                showTooltips: false
};

$(document).ready(function(){

    setInterval(function(){ get_data(); }, 1000);

});
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
Nasser
  • 11
  • 4

0 Answers0