Update Chart in Javascript using Chart.js

👍:0

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/

Leave a comment