Chartjs-How do I update the Chart.js automatically every 2 seconds?

0👍

A very practical (but not that efficient) solution would be JavaScript’s setInterval().

Here is an example:

setInterval(function() {
    let getData = $.getJSON('/value');
    getData.done(function(result) {

        var zeit = result.zeit;
        var flow = result.flow;
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: zeit,
                datasets: [{
                    data: flow,
                    label: "Flow>",
                    borderColor: "#0004cd",
                    fill: false
                }, ]
            }
        });
    });
}, 2000) // 2000 milliseconds = 2 seconds

This will get the information from the source you provide trough AJAX and will execute the same code you are using for your first render after every request.

The issue with this method would be that every time you update your chart, it will generate a request to the server you specified.

Leave a comment