Chartjs-How to update chart at the end of every for loop in Chart.js?

0👍

if you have a lot of update operations you should remove the animation duration from the chart. Read the paragraph “preventing-animations”

function bubble() {
    for (i = 0; i < num - 1; i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (ar[j] > ar[j + 1]) {
                var tmp = ar[j];
                ar[j] = ar[j + 1];
                ar[j + 1] = tmp;
                myChart.data.datasets[0].data[j] = ar[j];
                myChart.data.datasets[0].data[j + 1] = ar[j + 1];
                myChart.options.animation.duration = 0;
                myChart.update();
            }
        }
    }
}

The options.animation.duration should remove the animation duration

If it doesn’t works as intended you should wait for the update operations with a setInterval or something similar

0👍

Chart.js uses requestAnimationFrame to render the changes to charts.

So when whenever you say chart.update(), it won’t render the changes immediately, it will render the changes in next frame.

When you are calling chart.update() inside a for loop, the whole loop gets executed in a single cycle, so whats happening there is your chart data is getting updated in first iteration which is queued to be rendered in next frame, but without waiting for the next frame the data is getting updated again and so on.

By the time of next frame, your chart has only the final changes, all the intermediate changes were overwritten.

If you want each iteration of your change to show up in the rendering you should exactly make one change per frame. To do that for or while loops are not an option as they are synchronous.

You should be using a recursive function which waits for next frame before making the next change using requestAnimationFrame if you want snapshots or setTimeout if you want animation too.

You should be following the below template

(function iteration() {
  chart.update();

  // Wait for next frame for the changes to render and call the next iteration
  requestAnimationFrame(function () {
    iteration();
  });
})();

Leave a comment