0
votes

I have been using Chart.js Chart.js Documentation

I have a graph showing multiple lines. The graph is of a changing drug concentration per unit time (s), I would like to run this graph in a variety of scenario's ie, realtime, x2, x4, x8, etc So when the next second comes along I want the graph to update with the new calculated data and then REFRESH/update the chart.

//simDur is the duration i want the simulation to run for eg 1hr/3600secs
for(t=0; t < simDur; t++)
{
    timer(); //function awaits here for the next second to arrive
    generateData(); //calculate the new data yArr;
    myLineChart.addData(yArr, t); //yArr is an array of Y values, t=time
    myLineChart.update();  //update the chart with the new added data
}

the problem is the chart does not refresh until the finish of the for loop, I want the chart to display the updated data each second.

The documentation says update() should do the following...

Calling update() on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.

1
How are you waiting? Is it a busy loop? Is so you probably want to use setTimeout or setInterval instead of a for-loop.Spencer Wieczorek
I have a function as follows (function Forever() { var now = new Date(); var hh = now.getHours(); var mm = now.getMinutes(); var ss = now.getSeconds(); g_realTimeNow = (ss + (mm * 60) + (hh * 60 * 60)); //convert to secs console.log("Global time: " + g_realTimeNow); setTimeout(Forever, 1000); })();David Williamson

1 Answers

0
votes

If your timer(); contains the code in your comments i.e.

(function Forever() {
    var now = new Date();
    var hh = now.getHours();
    var mm = now.getMinutes();
    var ss = now.getSeconds();
    var g_realTimeNow = (ss + (mm * 60) + (hh * 60 * 60));
    //convert to secs
    console.log("Global time: " + g_realTimeNow);
    setTimeout(Forever, 1000);
})();

this doesn't actually wait for the setTimeout handler to complete before returning. So effectively what happens is that timer() is called simDur times without any delay.

Modify your code as below and you should get something closer to what you require (I've used setInterval, but you could also use setTimeout but it's going to be slightly more complicated)

var t = 0;
var interval = setInterval(function () {
    if (t >= simDur) {
        clearInterval(interval);
        return;
    }

    generateData(); //calculate the new data yArr;
    myLineChart.addData(yArr, t); //yArr is an array of Y values, t=time
    myLineChart.update();  //update the chart with the new added data

    t++;
}, 1000)

Fiddle - http://jsfiddle.net/xhequLjw/