简体   繁体   中英

Update Chart in Javascript using Chart.js

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.

If your timer(); contains the code in your comments ie

 (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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM